sarsnake
sarsnake

Reputation: 27733

Serializing form data doesn't work in asp.net mvc app

In my html I have

<h2>Title goes here</h2>

    @using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "myFormID" })) {
        <input type="text" id="testinput" name="testinput" />
        <input type="text" id="testinput2" name="testinput2" />

        <input type="button" value="click me" onclick="submitForm();" />
    }

in my js I have

function submitForm() { 

    dataString = $("#myFormID").serialize();

    alert(dataString);

    $.ajax({

        type: "POST",
        url: "/Controller/Action",
        data: dataString,
        cache: false,
        dataType: "json",

        success: function (data) {

            alert('success!');
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown);

        }

    }); 

}

In my controller file I have:

    public ActionResult Action()
    {
        return View();
    }



    [HttpPost]
    public ActionResult Action(string testinput, string testinput2)
    {
        return View();
    }

When clicked on "click me" button, I get the following error: "parsererror
Invalid JSON: "

What am I doing wrong? I am simply trying to pass form data to jquery .ajax.

The alert statement outpust "testinput=gdfgf&testinput2=gfgfd" which is the correct values I entered. SO the error seems to be when serializing.... I am using MVC 3 with razor...I had the impression that passing data between model/view and javascript code was made easier.

Upvotes: 1

Views: 3121

Answers (2)

Leons
Leons

Reputation: 2674

if your method accepts only int id as parameter, then dataString should be declared as

var dataString = { id: $("#myFormID").val() };

if you need to pass id and testinput as parameters, then use

var dataString = { id: $("#myFormID").val(), testinput: $("#testinput").val() };

The parameters and names in dataString mutch match the parameters of your action method.

Upvotes: 0

Ilia G
Ilia G

Reputation: 10221

I am almost positive that has nothing to do with the data you pass to the $.ajax call and everything with the data returned by /Controller/Action. Open up Fiddler and examine the response. it is likely malformed (or not JSON at all).

Upvotes: 2

Related Questions