Al.
Al.

Reputation: 875

Behavior of default model binder with custom object while model binding

In the below code my 'tc' object has been initialized after posting, but values are null. What is the root cause of the issue. Why is the default model binder doesn't attempt to populate the properties with incoming posted values? What restriction the default model binder has to behave like this?

  <form id="hello-world" action="/Home/Index">
        <label for="user">User  </label>
        <input id="user" type="text" name="user" required="required">
        <label for="city"> City </label>
        <input id="city" type="text" name="city" required="required">
        <label for="age"> Age </label>
        <input id="age" type="text" name="age" required="required">
        <input type="submit" value="Submit">
    </form>


 public ActionResult Index(TestClass tc)
   { 
     ViewBag.TCName = tc.user; // its null
     ViewBag.TCAge = tc.age; // its null
     ViewBag.TCCity = tc.city; // its null
     return View();
    }
public class TestClass
{
    public string user;
    public string city;
    public string age;
}

Upvotes: 0

Views: 85

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You should use properties and not fields on your view model:

public class TestClass
{
    public string User { get; set; }
    public string City { get; set; }
    public string Age { get; set; }
}

The default model binder can only bind to properties with public getters/setters and not with fields. It simply ignores fields and they will never be initialized.

Upvotes: 2

Related Questions