asp.net-mvc-4modelstatemodelbinder

Model binder wont pass checkbox value into integer property


My user model has an int property called active (its an int because I didn't create the model nor the database, its getting used as a boolean..). I'm creating the action /Users/Edit/ that will be editting the model, so I've got a form with a checkbox for the active property. When the submit button is pressed the model binder will put all the form data together into one single object and pass it as a parameter to /Users/Edit.

But when I try to save the changes to the database, I check ModelState.isValid and it returns false because the model binder won't change the boolean into an integer.

How can I solve this problem?


Solution

  • 1) Edit Db to make it a bit

    2) Change the property on your view model to a bool

    3) Use DisplayFor in your Razor View

    It will now automatically generate a checkbox and check it accordingly.