[英]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? 是否可以在ASP.NET MVC4 Razor项目的JavaScript文件中使用web.config设置,如下面的“serverPath”?
<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 我想根据调试或发布模式更改以下jQuery ajax调用的URL
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? 可以像查看一样从web.config中读取值并将其替换为.js文件吗?
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: 另一种方法是使用一个js文件,其中包含web.config为.net网站所做的配置:
configuration.js
: 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. 好吧,你可以将这个配置写成你的页面作为javascript或链接到脚本或合并并缩小为一个公共文件。 It would become part of your deployment process.
它将成为您部署过程的一部分。
Then use it as you would any js object: 然后像使用任何js对象一样使用它:
var request = $.ajax({
url: configuration.apiurl,
type: 'GET',
cache: false,
dataType: 'json'
});
Or some variant thereof. 或其一些变体。
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: 要传递给外部js文件,您需要使用函数来获取参数并通过视图调用它:
<script type="text/javascript">
getData('@ConfigurationManager.AppSettings["serverPath"]');
</script>
When your js file has something like this: 当你的js文件有这样的东西时:
function getData(path) {
var request = $.ajax({
url: path,
type: 'GET',
cache: false,
dataType: 'json'
});
return request;
}
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: 在视图中只需将其输入JS:
var request = $.ajax({
url: '@(Model.ServerPath)',
type: 'GET',
cache: false,
dataType: 'json'
});
Try this: 尝试这个:
var request = $.ajax({
url: '@(ConfigurationManager.AppSettings["serverPath"])',
type: 'GET',
cache: false,
dataType: 'json'
});
You could do that for ASP.NET MVC4 Razor this way: 你可以用这种方式为ASP.NET MVC4 Razor做到这一点:
@{
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.