ASP.NET MVC - server-side validation for value types
I have a model that contains value types (e.g. bool
, DateTime
, enums, etc) and I've marked the properties with the [Required]
attribute.
I load the page, don't supply a value for an开发者_JAVA技巧ything, and submit the form. Client-side validation is turned off. Obviously the ModelState
is invalid.
When the form is returned to the client however, these fields are populated with the type's default value (e.g. false
, DateTime.MinValue
, the first enum value, etc). This is not really what I want, I want the fields to stay empty.
Currently I'm getting round this by making the properties nullable (e.g. bool?
). Is this the "correct" thing to do? Or should I be doing something else to ensure that MVC isn't automatically populating value-type properties with the default value?
I'm assuming you want the fields in the form to remain empty on next visit - in which case Nullable types is one way to go yes. Strings is another.
Note: I tend not to use Enums in my ViewModel, but rather nullable ints - I find it easier.
Another trick is to leave 0 for Enums to be used in Combo boxes unmapped, and then add a "Please Select" (value=0) option. In this case you are better off without a nullable type since 0 is useful.
All of this works much better if you have a separate ViewModel from your Domain object - use Automapper of equivalent to map between them. This allows you to have one set of types in your ViewModel designed for your UI, without compromising what you have in your Domain Layer.
精彩评论