How to update JavaScript with the value from the web.config file in an ASP.NET MVC4 Razor project?

Is it possible to use a web.config parameter such as "serverPath" below in a JavaScript file in an ASP.NET MVC4 Razor project?

<appSettings>
  <add key="serverPath" value="http://myserver" />
</appSettings>

I would like to change the URL of the next jQuery ajax call depending on debug mode or release

  var request = $.ajax({
    url: 'http://myserver/api/cases',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });

Is it possible to read the value from web.config as View and replace it in the .js file?

+5
source share
5 answers

An alternative is to have a js file that contains your configuration the way web.config does for the .net website:

configuration.js:

var configuration = {
    apiurl: 'http://myserver/api/',
    someOtherSetting: 'my-value'
};

, javascript, script, . .

, js:

var request = $.ajax({
    url: configuration.apiurl,
    type: 'GET',
    cache: false,
    dataType: 'json'
});

- .

+5

, :

@ConfigurationManager.AppSettings["serverPath"]

js , :

<script type="text/javascript">
    getData('@ConfigurationManager.AppSettings["serverPath"]');
</script>

js - :

function getData(path) {
    var request = $.ajax({
        url: path,
        type: 'GET',
        cache: false,
        dataType: 'json'
    });

    return request;
}
+1

Ideally, you should read the value in the controller:

var serverPath = ConfigurationManager.AppSettings.Get("serverPath");

Then set the view model property with this value

myViewModel.ServerPath = serverPath;
return View(myViewModel);

And in the view, just pass it to JS:

var request = $.ajax({
    url: '@(Model.ServerPath)',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });
+1
source

Try the following:

var request = $.ajax({
    url: '@(ConfigurationManager.AppSettings["serverPath"])',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });
0
source

You can do this for ASP.NET MVC4 Razor this way:

@{
    var apiBaseUrl = ConfigurationManager.AppSettings.Get("ApiBaseUrl");
}

<script type="text/javascript">
    $(document).ready(function() {

      var request = $.ajax({
          url: '@apiBaseUrl/cases',
          type: 'GET',
          cache: false,
          dataType: 'json'
      });

    });
</script>
0
source

All Articles