Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to use a web.config setting 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 following jQuery ajax call depending upon debug or release mode

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

Is is possible to read the value from web.config like a View and substitute it in the .js file?

like image 926
ChrisP Avatar asked Mar 20 '13 16:03

ChrisP


3 Answers

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

configuration.js:

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

Well, you could either write this configuration into your page as javascript or link to the script or merge and minify into a common file. It would become part of your deployment process.

Then use it as you would any js object:

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

Or some variant thereof.

like image 53
Eben Roux Avatar answered Nov 03 '22 18:11

Eben Roux


Ideally, you would read the value in the controller:

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

Then set the view model's property with that value

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

And in the view simply feed it into JS:

var request = $.ajax({
    url: '@(Model.ServerPath)',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });
like image 1
Cloud SME Avatar answered Nov 03 '22 16:11

Cloud SME


Sure, use this in your view:

@ConfigurationManager.AppSettings["serverPath"]

For passing through to an external js file you need your function to have a parameter and call it via your view:

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

When your js file has something like this:

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

    return request;
}
like image 1
Linus Caldwell Avatar answered Nov 03 '22 18:11

Linus Caldwell