I have a Model Like this
public int Id {get;set;}
[Required]
public string FirstName{get; set}
[Required]
public string LastName{get; set}
The Id is auto generate in DB. when I want call Create action The ModelState says that "The Id field is required"!!!! I Found this for my problem but it not clean solution. Is there an other way to solve this?
Is there a way that I change Mvc ModelBinder behavior for value types?
The best solution to this problem is to use a view model. A view model is a class that you specifically design to meet the requirements of your view. So your controller action will take this view model as parameter. Simply stop passing your domain models to your views. That's it.
And if you don't want to follow good practices and use view models you could disable this implicit validation by adding the following to your Application_Start
:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
another hack is to exclude this property from binding using the [Bind(Exclude = "Id")]
attribute. Yeah, it's a hack but if you don't follow good practices you will have to live with hacks.
Although @DarinDimitrov suggested a good option to use View Models, In addition to that answer. Also, consider this option only when you don't want to create the View-Model
How about ModelState["Id"].Errors.Clear();
in your Post
Action Method ?
You can also set the property type to Nullable<T>
, and then just manually enforce any required validation you might need to do before working with the database.
public int? Id {get;set;}
Further Reading:
来源:https://stackoverflow.com/questions/17143001/why-mvc-model-binder-set-required-for-int-long-values