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

冷暖自知 提交于 2019-12-10 10:59:39

问题


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?


回答1:


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.




回答2:


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 ?




回答3:


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:

  • Unrequired property keeps getting data-val-required attribute
  • ASP.NET MVC optional field being treated as required
  • "The Id field is required" validation message on Create


来源:https://stackoverflow.com/questions/17143001/why-mvc-model-binder-set-required-for-int-long-values

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