2

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 anything, 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?

2
  • Or maybe I'm going to be told I should be using a View Model class which only has strings...? Unfortunately it's a bit late for that, partly due to requirements and partly due to my inexperience. I'll save that til the next project! Commented Jun 28, 2011 at 9:04
  • I would stick with the nullable option. This is something I've wanted to do and I couldn't find an easier solution apart from perhaps not using the MVC clientside validation and creating my own. That seemed like too much work though. Commented Jun 28, 2011 at 11:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.