简体   繁体   English

Ajax 调用未命中控制器操作

[英]Ajax call not hitting controller action

I am trying to send a FormCollection to an action in my controller but the action is never being hit.我正在尝试将FormCollection发送到我的控制器中的一个动作,但该动作从未被击中。

Form:形式:

<form class="form-horizontal" role="form" id="TestForm" onsubmit="return false">
<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <input type="text" name="Blah1" />
            <input type="text" name="Blah2" />
        </div>
        <input id="SubmitButton" type="submit" value="Submit" />
    </div>
</div>

jQuery/Ajax: jQuery/Ajax:

$(document).ready(function () {
    $("#SubmitButton").click(function () {
        var form = $("#TestForm").serialize();


        $.ajax({
            url: "/Calculator/Post",
            type: "POST",
            data: form,
            dataType: 'json',
            success: function () {
                alert("Success");
            },
            error: function () {
                alert("Error");
            }
        });
    });
});

Controller Action:控制器动作:

[HttpPost]
public JsonResult Post(FormCollection form)
{
    return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}

The only thing that happens is the browser alerts the error message.唯一发生的事情是浏览器警告错误消息。 Am I missing something that is causing the action to never be hit?我是否错过了导致动作永远不会被击中的东西?

Your code should work fine as posted in the question.您的代码应该可以正常工作,如问题中所述。 The only issue is see is how you are building the url manually which might cause 404 issues sometimes depending on your current url/page.唯一的问题是您如何手动构建 url,这有时可能会导致 404 问题,具体取决于您当前的 url/页面。 You should be using the Url.Action helper method to build the urls which will take care of building the correct relative url regardless of which page you are currently in.您应该使用Url.Action帮助器方法来构建 url,无论您当前在哪个页面,它都会负责构建正确的相对 url。

serialize() method is good enough to send your form data. serialize()方法足以发送表单数据。 It should work fine( go ahead and try it ).它应该可以正常工作(继续尝试)。 you do not need to call the serializeArray and then stringify it as suggested by the accepted answer !您不需要按照接受的答案的建议调用serializeArray然后将其字符串化!

$.ajax({
    url: "@Url.Action("Post","Calculator")",
    type: "POST",
    data: $("#TestForm").serialize(),
    dataType: 'json',
    success: function () {
        alert("Success");
    },
    error: function () {
        alert("Error");
    }
});

If you are making this ajax call in an external js file, you may consider passing the base url to the js file and use that to build the relative url to your action method as described in this answer .如果您在外部 js 文件中进行此 ajax 调用,您可以考虑将基本 url 传递给 js 文件,并使用它来构建相对 url 到您的操作方法,如本答案所述

Also, in your action method, you do not need to pass the JsonRequestBehavior.AllowGet parameter to the Json method as your Action method is marked with [HttpPost]此外,在您的操作方法中,您不需要将JsonRequestBehavior.AllowGet参数传递给Json方法,因为您的 Action 方法标有[HttpPost]

[HttpPost]
public JsonResult Post(FormCollection form)
{
    var item =form["Blah1"];
    return Json(new { success = true });
}

.serialize()方法创建一个采用标准 URL 编码表示法的文本字符串。 serializeArray () 方法创建一个 JavaScript 对象数组,准备编码为 JSON 字符串。

var form = JSON.stringify($("#TestForm").serializeArray());

Make sure your controller Action Method or Method's argument data type is same as the data type of variable which is being post.确保您的控制器 Action Method 或 Method 的参数数据类型与正在发布的变量的数据类型相同。

Example:例子:

This will not work because in controller the InsertScore method receiving char as Answer data type but we are sending 'abc' which is not a character because char length is 2 byte so only 'a' or 'ab' can be sent in this case.这将不起作用,因为在控制器中,InsertScore 方法接收字符作为应答数据类型,但我们发送的不是字符的“abc”,因为字符长度为 2 个字节,因此在这种情况下只能发送“a”或“ab”。

Ajax Post:阿贾克斯邮报:

          $.ajax({
                  type: 'POST',
                  url: '/Home/InsertScore',
                  data: { Email: Em, Row: i, Answer: 'age' }
              });

Controller:控制器:

    [HttpPost]
    [WebMethod]
    public void InsertScore(string Email ,string Row,char Answer)
    {
     //do something here
    }

The correct way is.正确的方法是。

Ajax Post:阿贾克斯邮报:

        $.ajax({
              type: 'POST',
              url: '/Home/InsertScore',
              data: { Email: Em, Row: i, Answer: 'a' }
          });

Controller:控制器:

    [HttpPost]
    [WebMethod]
    public void InsertScore(string Email ,string Row,char Answer)
    {
      //do something here
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM