I was trying to create a simple input page with two date inputs, but @Html.EditorFor would only display a simple text input. Here's what I came with after reading some docs.

Custom Model Field Editors In Mvc3

I always wondered why, in views, the MVC's Html helper would offer a "EditorFor" method, when there were already other methods like "TextBoxFor" which would display the same input. However, I was lazy to investigate.

Until I had to. I was making a simple view containing two date inputs, whose values would be validated before using them to redirect to another view. I created a View Model for this porpuose which looks exactly like this:

public class KpiIndex
{
    [Display(Name = "Fecha Inicial")]
    [DataType(DataType.Date, ErrorMessage="La fecha de inicio no es válida")]
    [Required(AllowEmptyStrings=false, ErrorMessage="Introduce fecha de inicio por favor")]
    [DisplayFormat(ApplyFormatInEditMode=true, ConvertEmptyStringToNull=true, DataFormatString="{0:dd/MMMM/yyyy}")]
    public DateTime StartDate { get; set; }

    [Display(Name = "Fecha Final")]
    [DataType(DataType.Date, ErrorMessage = "La fecha final no es válida")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Introduce fecha final por favor")]
    [DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:dd/MMMM/yyyy}")]
    public DateTime EndDate { get; set; }
}

I made sure I specified a data type. I was not sure why, I just thought if I did it would just work, that MVC 3 would know that I explicitly wanted a Date input and would display such in my views. So I went directly to write my view, the exact code for this fragment was:

<div>
    <p class="editor-label">
        @Html.LabelFor(model => model.StartDate)
    </p>
    <p class="editor-field">
        @Html.EditorFor(model => model.StartDate, new { @class = "input_medium"})
    </p>
</div>
<div>
    <p class="editor-label">
        @Html.LabelFor(model => model.EndDate)
    </p>
    <p class="editor-field">
        @Html.EditorFor(model => model.EndDate, new { @class = "input_medium"})
    </p>
</div>

However, I quickly noticed it was not displaying an input of type date (for I configure them through css and js using css selector input[type='date']). WHY?? GOD WHY??

It turns out DataTypeAttributte for models is a hint, and now that you have the hint, it would be easier to work with it. But the work is up to you, no up to MVC 3. Why in the world did I think it would be the other way?

Ok, so if DataTypeAttributte is just a hint, what hint are we giving? Well, I specified [DataType(DataType.Date)] so the hint is Date. This hint will be used to find a DisplayTemplate (when you use @Html.DisplayFor) called Date.cshtml in Views/Shared/DisplayTemplates and an EditorTemplate (when you use @Html.EditorFor) called Date.cshtml in Views/Shared/EditorTemplates. This "templates" are nothing else but partial views used for specialized display of info and inputs.

Right now, I'm just interested in customizing the input, so I create the desired template, take a look:

/Views/Shared/EditorTemplates/Date.cshtml

Remember this just a partial view, so we anotate it with our model (which will be a DateTime object, since that's what we want to show) and then display a textbox for it. The complete code is shown just below:

/Views/Shared/EditorTemplates/Date.cshtml

@model DateTime?
@Html.TextBox(string.Empty, string.Format("{0:dd/MMMM/yyyy}", Model), new {type = "date"})

As you can see, the model was a Nullable<DateTime>, this is because in the case you have not yet filled your model (and so, it's null) MVC would throw and exception because you can't asign null to a DateTime variable, but I'm sure you already know that. I also specified the format the date would use to be shown, and customized the type attribute of the input so it can be correctly configured by my code.

That's it. Now, whenever you display an editor for a field which have been specified as having a DataType of Date, this template will rendered instead of a regular textbox.

I hope someone finds this useful. Happy coding!

Posted by: fabzter
Last revised: 05 Sep, 2012 04:51 PM History

Comments

Josephsl
Josephsl
20 Aug, 2016 02:10 AM

Wigied iwjw iwj wjwoj wk dncsgkfw http://ghfwijofhe38y39204irjfenjnw9.retwyu

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview