javascript jQuery Ajax 无法调用 MVC 4 控制器方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17173635/
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-10-27 07:22:29  来源:igfitidea点击:

jQuery Ajax failing to call to MVC 4 Controller method

javascriptjqueryajaxasp.net-mvc-4

提问by DrBowe

I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.

我正在尝试使用 jQuery 以便在单击某个按钮后触发 Ajax 调用。我已经阅读了几个可能遇到的语法和问题的示例,但未能找到适合我的原因的可行解决方案。这是代码。

Controller Method: (HomeController.cs)

控制器方法:(HomeController.cs)

    [HttpPost]
    public JsonResult ChangeCompany(string companyCode)
    {
        return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
    }

jQuery Code:

jQuery 代码:

    function changeCompany(company) {
    $.ajax({
        url: '@Url.Action("ChangeCompany", "Home")',
        type: 'POST',
        data: JSON.stringify({ companyCode: company }),

        success: function (data) {
            alert("Company: " + data);
        },
        error: function (req, status, error) {
            alert("R: " + req + " S: " + status + " E: " + error);
        }
    });
}

And finally, I'm calling this function with:

最后,我使用以下命令调用此函数:

$('.companyButton').click(function () {
    compCode = $(this).text();
    debug("Click event --> " + $(this).text());
    changeCompany(compCode);
});

My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found

我的调试消息正确显示,并且 Ajax 调用不断失败并显示以下警报: R: [object Object] S: error E: Not Found

I'm not entirely sure what to make of that.

我不完全确定该怎么做。

I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.

我知道关于这个主题有几个问题,但似乎没有一个能解决我的问题,老实说,我不确定这些代码块有什么问题。任何见解将不胜感激。

EDIT: In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all

编辑:如果值得注意,这是针对移动设备的。在 Windows 8 Phone Emulator (Internet Explorer) 和 jQuery Mobile 上进行测试。不确定这是否会影响 Ajax

EDIT 2: After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")'is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?

编辑 2:在查看原始网络调用后,它似乎'Url.Action("ChangeCompany", "Home")'没有被转换为正确的 URL,而是被直接调用,就好像它是原始 URL 文本一样。这是由于过时的 jQuery 还是其他一些因素?

回答by Chamika Sandamal

Ok with your EDIT2 it seems you are using url: '@Url.Action("ChangeCompany", "Home")',in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files

好的,您的 EDIT2 似乎是url: '@Url.Action("ChangeCompany", "Home")',在单独的 JavaScript 文件中使用的。你只能在 .cshtml 文件中编写 razor 代码,它在 .js 文件中不起作用

回答by Bhushan Firake

You are missing some important parameters in your AJAX call. Change your AJAX call as below:

您在 AJAX 调用中缺少一些重要参数。更改您的 AJAX 调用如下:

function changeCompany(company) {
    $.ajax({
              url: '@Url.Action("ChangeCompany", "Home")',
              type: 'POST',
              data: JSON.stringify({ companyCode: company }), 
              success: function (data) {
                       alert("Company: " + data);
                        },
             error: function (req, status, error) {
                       alert("R: " + req + " S: " + status + " E: " + error);
                        }
          });}

You can then annotate your controller method with [HttpPost]attribute as below;

然后,您可以使用[HttpPost]如下属性注释您的控制器方法;

 [HttpPost]
 public JsonResult ChangeCompany(string companyCode)
 {
   return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
 }

回答by InspiredBy

Note that your action is not returning companyCodedirectly. You're assigning it to Json resultproperty therefore In your success function to display result you need to have:

请注意,您的操作不会companyCode直接返回。您将它分配给 Jsonresult属性,因此在您的成功函数中显示结果,您需要:

success: function (data) 
  {
     alert("Company: " + data.result);
  }

Also this: E: Not Foundtells me that you may have some routing issues. If you set a break point inside of your ChangeCompanyAction, is it being hit ?

还有这个:E: Not Found告诉我你可能有一些路由问题。如果你在你的ChangeCompanyAction里面设置了一个断点,它会被击中吗?