2013-03-20 66 views
5

是否可以在ASP.NET MVC4 Razor項目的JavaScript文件中使用下面的「serverPath」之類的web.config設置?如何使用ASP.NET MVC4 Razor項目中的web.config文件中的值更新JavaScript?

<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' 
    }); 

是可以從web.config中讀取值像查看和替換它在.js文件中?

+0

沒有任何問題的答案能幫你嗎? – 2013-03-22 08:14:42

回答

5

另一種方法是讓一個js文件co ntains在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' 
}); 

或其某種變體。

+0

雖然這會起作用,但我更願意將所有配置信息集中在web.config文件中,該文件可以自動爲調試和發佈模式配置不同的配置。 – ChrisP 2013-03-20 16:59:42

+0

爲了允許爲不同的配置模式選擇不同的版本(debug/release/etc),你可以使用「configurationFileName」的web.config設置並在configuration.debug.js和configuraiton.release.js之間切換,作爲appSetting。然後使用該值來動態選擇靜態JS文件的路徑。 – Arkaine55 2015-11-18 21:25:37

+0

這當然是一個選項@ Arkaine55。對於我們的自動構建場景,我們將模板配置爲生成正確的配置文件。它*確實*有道理得到不同版本的文件,雖然:) – 2015-11-19 04:14:35

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; 
} 
0

試試這個:

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

由於JavaScript處於鏈接到視圖中的單獨.js文件中,因此它不會顯示此功能。 @ConfigurationManager ...仍然在渲染頁面中。 – ChrisP 2013-03-20 16:40:38

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' 
    }); 
+0

這是一個鏈接到View的獨立JavaScript文件,因此JavaScript不在視圖中。我不認爲在.js文件中可以訪問Modle,但我不確定。 – ChrisP 2013-03-20 16:36:31

+0

在這種情況下,您將使用Linus的方法並將其傳遞到您的JS文件中的方法中: 2013-03-20 17:07:06

0

你可以這樣做,對於ASP.NET MVC4剃刀:

@{ 
    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> 
相關問題