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

余生颓废 提交于 2019-12-06 14:17:03

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!