4

I have the following code:

jQuery:

$.ajax({
    url: '/personcontroller/getperson',
    cache: false,
    type: "POST",
    data: $('#person').serialize(),
    success: function(data) {
      alert('yay');
    }
    });
});

Controller:

public ActionResult getPerson(Person person)
{
    return new Json(person);
}

Html Form/Spark:

<form id="person">
   <input id="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
   <input id="person.Name" value="${ViewData.Model.Person.Name}"></input>
   <input id="person.Age" value="${ViewData.Model.Person.Age}"></input>
   <input value="${ViewData.Model.Person.Gender}"></input>
</form>

When I POST the ajax call with the form, and put a break point in my action. The person object is not being populated with the input values, I feel like I am overlooking something really simple... Can you please point it out to me :|

2 Answers 2

5

Inputs need a name attribute to post correctly. You should add a name attribute that matches the Id.

<form id="person">
   <input id="person.Id" name="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
   <input id="person.Name" name="person.Name" value="${ViewData.Model.Person.Name}"></input>
   <input id="person.Age" name="person.Age" value="${ViewData.Model.Person.Age}"></input>
</form>
Sign up to request clarification or add additional context in comments.

4 Comments

@tvanfosson: You mean id attribute.
Do i need the name attribute and the id attribute or will it work with just name :)?
My bad -- I just looked it up because I wasn't sure and the MVC helpers do replace the dot in the id with an underscore. Not strictly necessary, but it helps with jQuery.
You only need the name, but if you want to access it with javascript having the id is handy.
2

You should use:

public ActionResult getPerson([Bind(Prefix="person")]Person person)

EDIT

And as Michael Gattuso noticed, you should populate name property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.