5

I'd like to use model binding to keep my controllers looking cleaner, you can see how much nicer it is using model binding:

public ActionResult Create(Person personToCreate)
{
    //Create person here
}

vs

public ActionResult Create(string firstName, string lastName, string address, string phoneNum, string email, string postalCode, string city, string province, string country)
{
    //Create person here
}

When doing model binding, we can just use a form with the correct names in the Html.TextBox("")

What about jquery? How can I make sure that when I do a $.post(url, data, callback, dataType) or a $.ajax(options) call to Create(Person personToCreate) that the Person object gets filled properly?

1 Answer 1

4

You need to:

  1. Make the property names in data match the argument/property of bound type names.
  2. Always supply a value for all non-nullable arguments/properties of bound type.

Number 2 is the big one in terms of why binding to person can behave differently than specifying individual action arguments for each property. If you have a type with a non-nullable property called "Foo", then failing to supply a foo item in your form will prevent binding.

Sign up to request clarification or add additional context in comments.

2 Comments

And the only way to get around that is Custom Model Binders?
Or change the property type to nullable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.