Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 495
chowe991 Avatar asked Jan 18 '26 22:01

chowe991


1 Answers

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'
});
like image 177
Jason P Avatar answered Jan 20 '26 11:01

Jason P