在 MVC 4 中使用 $.ajax 发出 AJAX 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13019778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:51:36  来源:igfitidea点击:

Make an AJAX request using $.ajax in MVC 4

ajaxasp.net-mvcasp.net-mvc-4razor

提问by Mason

I am trying to make an AJAX request using $.ajax in MVC 4 with Razor. I'm not sure how to implement it.

我正在尝试在带有 Razor 的 MVC 4 中使用 $.ajax 发出 AJAX 请求。我不确定如何实现它。

Using this videoI 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:

使用此视频,我能够成功进行返回数据的链接驱动调用,但我似乎无法从 jquery 函数内部执行相同的操作。我似乎无法找到有关如何执行此操作的任何基本示例。这就是我正在使用的:

HomeController.cs

家庭控制器.cs

        public string test(){
             return "It works";
        }

View.cshtml

查看.cshtml

function inventory(dealerID) {
    $.ajax({
        url: '@Url.Action("HomeController","test")',
        data: {dealerID: dealerID},
        type: 'POST',
        success: function(data) {
            process(data);
        }
    });
}

回答by McGarnagle

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 HttpPostattribute. Try this:

你只需要把它变成一个ActionResult. 此外,如果您使用 Ajax POST,则需要使用HttpPost属性标记操作。尝试这个:

[HttpPost]
public ActionResult test(string dealerID)
{
    return Content("It works");
}

EditActually, there are a few other problems with the syntax.

编辑实际上,语法还有其他一些问题。

  1. Url.Actionhas the controller/action parameters in the wrong order -- should be "ActionName" first, then "ControllerName"
  2. For Url.Action, if the controller class is "HomeController", then you need just "Home"
  3. The JQuery options syntax is wrong -- should be success: function(data) {}.
  1. Url.Action控制器/动作参数的顺序错误——应该先是“ActionName”,然后是“ControllerName”
  2. 对于Url.Action,如果控制器类是“HomeController”,那么您只需要“Home”
  3. JQuery 选项语法错误 - 应该是success: function(data) {}.


$.ajax({
    url: '@Url.Action("test", "Home")',
    data: {dealerID: dealerID},
    type: 'POST',
    success: function(data) {
        alert(data);
    }
});