Asp.net mvc 4 Display empty editor for default values using EditorFor

Asp.net mvc 4 Display empty editor for default values using EditorFor,asp.net-mvc-4,Asp.net Mvc 4,My model has a property: [Required] [DataType(DataType.Date)] public DateTime BirthDate { get; set; } which I'm displaying in my (strongly typed) view using EditorFor: <p>@Html.LabelFor(m => m.BirthDate) @Html.EditorFor(m => m.BirthDate) @Html.ValidationMessageFor(m => m.BirthDate) </p> When the view is rendered the birth date textbox shows "01.01.0001", i.e. the DateTime default value. This is correct if the BirthDate value is not initialized, however I want the

My model has a property:

[Required]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

which I'm displaying in my (strongly typed) view using EditorFor:

<p>@Html.LabelFor(m => m.BirthDate)
   @Html.EditorFor(m => m.BirthDate)
   @Html.ValidationMessageFor(m => m.BirthDate)
</p>

When the view is rendered the birth date textbox shows "01.01.0001", i.e. the DateTime default value. This is correct if the BirthDate value is not initialized, however I want the textbox to be empty in that case.

What is the standard way to do this? I don't want to use Nullable<DateTime> in my model because BirthDate is a required value.


#1

You're looking for the DisplayFormat attribute most likely. Also, unless you're using a DateTime?/Nullable<DateTime> you're probably going to end up with Jan 1 (since there can't be a null value).

If you do decide to use DateTime?/Nullable<DateTime> enforcing a value using [Required] should avoid any issues you're speaking of, so if that was your hesitation I wouldn't be too worried.

As a final alternative, you can override the DateTime.cshtml (or Date.cshtml since you're using the DataType attribtue) template (~/Views/Shared/DisplayTemplates/) and make the textbox empty when populated with default(DateTime). e.g.

@model DateTime
@Html.TextBox(String.Empty, Model == default(DateTime) ? String.Empty : Model)

(Or something along those lines)


#2

DisplayFormat doesn't help because I can't define a format to display "nothing", and I'd rather not use a Nullable because changing the business objects to accomodate View functionality doesn't feel like clean separation of concerns. The template (placed in ~/Shared/EditorTemplates) however does excactly what I need. Thanks!

#3

@matk: keep in mind that business objects (like POCOs) are usually kept server-side and VMs are used to display (then using something like AutoMapper makes it easier to marry the two). With that said, making a VM have a nullable property isn't all that bad as it will just end up populating the POCO in your action, while keeping the look and feel within the UI.

#4

True, if a ViewModel is used. I like the template based approach better because it will take care of all instances where a DateTime is displayed, whether a ViewModel is used or not.