2012-06-23 49 views
0

嗨,在一個JavaScript中的ASP.NET MVC標籤?

我需要提取適當的URL的AJAX調用,這是我在我的js文件添加:

var GetLocationByParentPath = '<%= Url.Content("~/Location/GetLocationsByParent") %>'; 

的ASP.NET MVC標籤但我們不運行所以現在是這樣的問題,我該如何填充GetLocationByParentPath正確的值?

BestRegards

回答

2

你的問題是,你要實現這一目標是不支持的東西,你不能使用內部js文件的C#代碼。

但是,你可以做你的aspx文件(或CSHTML)和js文件可以與溝通,所以你有3種選擇:

1。一個參數添加到您的函數在接受URL

的JS裏面的js文件:

function yourfunction(url) 
{ 
    var GetLocationByParentPath = url; 
} 

您的aspx裏:

<script> 
    yourfunction('<%= Url.Content("~/Location/GetLocationsByParent") %>'); 
</script> 

2。添加包含此網址的全局變量JS:

您的aspx裏:

<script> 
    var getLocationsUrl = '<%= Url.Content("~/Location/GetLocationsByParent") %>' 
    yourfunction(); 
</script> 

的JS裏面(確保定義getLocationsUrl你的函數運行前):

function yourfunction() 
{ 
    var GetLocationByParentPath = getLocationsUrl ; 
} 

3。使用完整的硬編碼URL(壞的重構,但簡單的解決方案:JS裏面

(確保定義getLocationsUrl你的函數運行前):

var GetLocationByParentPath = '/Location/GetLocationsByParent'; 

希望這helpes

+0

我有一個$(document).ready(function()in the js file and its here the funtion is executed。如果我在aspx頁面的$(document).ready(function()中放置替代方法2,它會被永遠執行? – Banshee

+0

這取決於您是否在放置$(document).ready或之前包含js文件。無論如何,您不必在aspx中使用$(document).ready就可以設置ag lobal變量,只有在整個頁面加載後纔會發生。只是在你包含你的js文件之前做出這個任務。 –