在 MVC 4 中使用 $.ajax 发出 AJAX 请求 [英] Make an AJAX request using $.ajax in MVC 4
问题描述
我正在尝试在带有 Razor 的 MVC 4 中使用 $.ajax 发出 AJAX 请求.我不确定如何实现它.
I am trying to make an AJAX request using $.ajax in MVC 4 with Razor. I'm not sure how to implement it.
使用此视频我能够成功地进行链接驱动的调用返回的数据,但我似乎无法从 jquery 函数内部做同样的事情.我似乎找不到有关如何执行此操作的任何基本示例.这就是我正在使用的:
Using this video I was able to successfully make a link-driven call that returned data, but I can't seem to do the same thing from inside a jquery function. I can't seem to find any basic examples of how to do this. This is what I am working with:
HomeController.cs
public string test(){
return "It works";
}
View.cshtml
function inventory(dealerID) {
$.ajax({
url: '@Url.Action("HomeController","test")',
data: {dealerID: dealerID},
type: 'POST',
success: function(data) {
process(data);
}
});
}
推荐答案
您只需要将其设为 ActionResult
.此外,如果您使用 Ajax POST,则需要使用 HttpPost
属性标记操作.试试这个:
You just need to make it an ActionResult
. Also, if you're using an Ajax POST, then the action needs to be marked with the HttpPost
attribute. Try this:
[HttpPost]
public ActionResult test(string dealerID)
{
return Content("It works");
}
编辑实际上,语法还有一些其他问题.
Edit Actually, there are a few other problems with the syntax.
Url.Action
的控制器/动作参数顺序错误——应该先是ActionName",然后是ControllerName"- 对于
Url.Action
,如果控制器类是HomeController",那么你只需要Home" - JQuery 选项语法错误 -- 应该是
success: function(data) {}
.
Url.Action
has the controller/action parameters in the wrong order -- should be "ActionName" first, then "ControllerName"- For
Url.Action
, if the controller class is "HomeController", then you need just "Home" - The JQuery options syntax is wrong -- should be
success: function(data) {}
.
$.ajax({
url: '@Url.Action("test", "Home")',
data: {dealerID: dealerID},
type: 'POST',
success: function(data) {
alert(data);
}
});
这篇关于在 MVC 4 中使用 $.ajax 发出 AJAX 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!