[英]Call ASP.NET MVC controller action from seperate javascript file
What url syntax should I be using to ensure controller actions are properly resolved in a jQuery ajax call? 我应该使用什么url语法来确保控制器动作在jQuery ajax调用中得到正确解决? For example, the following syntax to invoke Method1 on HomeController works while running site in Visual Studio:
例如,在Visual Studio中运行站点时,以下语法可在HomeController上调用Method1:
$.ajax({
type: 'GET',
url: "Home/Method1?lparam1=" + 1+ "¶m2=" + 2, // my problem
dataType: 'json',
cache: false,
success: function(){ alert("success");}
});
But when I deploy site on IIS, I get HTTP 404 telling me controller actions can not be resolved. 但是,当我在IIS上部署站点时,我收到HTTP 404告诉我无法解决控制器操作。
TIA. TIA。
I would let MVC generate the link for you: 我会让MVC为您生成链接:
url: '@Url.Action("Method1", "Home")?lparam1=' + encodeURIComponent(1) + ...
If your JS in an external file, you could set a global variable with the URL in your page and let the external file read it. 如果您的JS位于外部文件中,则可以在页面中使用URL设置一个全局变量,然后让外部文件读取它。 Also, if your VS and IIS urls are different, you can give you site a Virtual Directory name in the project properties so that it matches your IIS directory, or better, yet, just have your project use IIS instead of Cassini (the built-in web server).
另外,如果您的VS和IIS网址不同,则可以在项目属性中为您的站点提供虚拟目录名称,以使其与您的IIS目录匹配,或者更好,但是,只需让您的项目使用IIS而不是Cassini(在Web服务器中)。
只需将网址行更改为:
url: "/Home/Method1?lparam1=" + 1+ "¶m2=" + 2,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.