What does it mean for a property to be [Required] and nullable?

六月ゝ 毕业季﹏ 提交于 2019-11-26 15:32:03

The reason for making a property nullable and marked with the [Required] attribute is to protect against under-posting attacks. It also allows you to display an initial empty value in the view rather than the default value for the property. This is typically done with value type properties in view models.

An under-posting attack is where a malicious user modifies the request to omit a value for the property in the request. If the property was DateTime (not nullable), then the DefaultModelBinder will initialize the value its default (01/01/0001) and no ModelState error would be generated. As a result, that value may then be saved even though its not what you may be expecting.

If the property is DateTime? (nullable) and [Required], then if a malicious user did omit the property in the request, then a ModelState error will be generated because a value is expected in the request, and the view would be returned, therefore the invalid data will not be saved.

Refer also Brad Wilson's article Input Validation vs. Model Validation in ASP.NET MVC and the section titled The "Under-Posting" Problem.

It's nullable so the form doesn't display an initial value like 0001-01-01T00:00:00 that has no meaning.

It's required to force the user to enter something.

Required is a data annotation for the view. The view will require it to have a value prior to accepting a form post.

That the value is nullable is related to what is allowed in the database. A value may be null in the database, or the value may be persisted as null.

They are separate aspects.

It is required for client validation but nullable for DB mapping

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