简体   繁体   中英

How to serialize model, pass it to MVC controller in ajax request

I'm trying to pass my page's model to my controller for processing. After processing the information, I want to update the div of id "savedText" to display "Billing Information saved successfully."

I have this in my view

function testingFunction() {
    var obj = $('testForm').serialize();

    $.ajax({
        url: '@Url.Action("TestingFunction", "BuildGiftCard")',
        dataType: 'json',
        success: function (result) {
            $("#savedText").html(result);
        },
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(obj)
    });

    return false;
}

and I have this in my controller:

[HttpPost]
public JsonResult TestingFunction(PurchaseModel model)
{
    return Json("Billing information saved successfully.");
}

what am I doing wrong?

When "inspecting element" in chrome, in the network tab, it's saying that my controller method isn't found.

Also, it's important for me to get the entire model from the view into the controller's function (TestingFunction in this case) so that I can get the form information and save it. I'm trying the .serialize() function but that results in obj = (empty string).

Three things:

  1. $('testForm') should probably be $('.testForm') or $('#testForm') . As it is you're trying to select a <testForm></testForm> .
  2. If you're just sending the form, it doesn't need to be json.
  3. Try doing a post request:

$.ajax({
    url: '@Url.Action("TestingFunction", "BuildGiftCard")',
    dataType: 'json',
    success: function (result) {
        $("#savedText").html(result);
    },
    data: $('#testForm').serialize(),
    type: 'POST'
});

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