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.
質問
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?
解決
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.
他のヒント
Let's assume worst case that you cannot change your Db to a bool. Then you would use a View Model to perform the data transformation for you.
Say your user model is such:
public class StaticModel {
public string description { get; set; }
public int IsActive { get; set; }
}
Then you create a view model (facade style):
public class StaticModelFacade {
StaticModel _value;
public StaticModelFacade(StaticModel value) {
_value = value;
}
public string description {
get {return _value.description;}
set {_value.description = value;}
}
public bool IsActive {
get { return _value.IsActive = 1; }
set { _value.IsActive = value ? 1 : 0 }
}
}
Your view now binds to a bool and all is wired up Ok.