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?
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.
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'
});
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With