5

是否可以在 ASP.NET MVC4 Razor 项目的 JavaScript 文件中使用 web.config 设置,例如下面的“serverPath”?

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

我想根据调试或发布模式更改以下 jQuery ajax 调用的 URL

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

是否可以像 View 一样从 web.config 读取值并将其替换为 .js 文件?

4

5 回答 5

5

另一种方法是拥有一个 js 文件,其中包含您的配置,就像 web.config 为 .net 网站所做的那样:

configuration.js

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

好吧,您可以将此配置作为 javascript 写入您的页面,也可以链接到脚本或合并并缩小到一个通用文件中。它将成为您部署过程的一部分。

然后像使用任何 js 对象一样使用它:

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

或者它的一些变体。

于 2013-03-20T16:25:27.837 回答
1

当然,在您的视图中使用它:

@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;
}
于 2013-03-20T16:17:17.017 回答
1

理想情况下,您会读取控制器中的值:

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

然后使用该值设置视图模型的属性

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

在视图中只需将其输入 JS:

var request = $.ajax({
    url: '@(Model.ServerPath)',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });
于 2013-03-20T16:18:55.437 回答
0

试试这个:

var request = $.ajax({
    url: '@(ConfigurationManager.AppSettings["serverPath"])',
    type: 'GET',
    cache: false,
    dataType: 'json'
  });
于 2013-03-20T16:18:11.860 回答
0

您可以通过以下方式为 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>
于 2013-09-24T15:11:18.710 回答