简体   繁体   中英

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

What does it mean for a property to be [Required] and nullable? (example below) It seems that if it is [Required] it couldn't possibly be null (no value), and if it is able to be null it couldn't possibly be [Required] .

[Required]
public DateTime? OrderDate { get; set; }

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.

它是客户端验证所required ,但对于数据库映射是nullable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM