2012-06-23 43 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文件之前做出这个任务。 –