简体   繁体   中英

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.

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:

$(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. 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.

serialize() method is good enough to send your form data. 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 !

$.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 .

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]

[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.

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.

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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