Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MVC Model Binder set required for int, long values?

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?

like image 687
M.Azad Avatar asked Dec 07 '25 23:12

M.Azad


1 Answers

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.

like image 103
Darin Dimitrov Avatar answered Dec 10 '25 13:12

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!