Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display datetime model property as Short date time string

I'm new with MVC2, and am having a formatting problem. I have a DateTime property in my Employee model that I would like displayed with the Short Date Time.

This however, does not appear to be the correct method.

1 <div class="editor-field">
2    <%: Html.TextBoxFor(model => model.DateRequested.ToShortDateString()) %>
3    <%: Html.ValidationMessageFor(model => model.DateRequested) %>
4 </div>

Line 2 throws this exception:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

What is the correct way to handle formatting in mvc?

like image 707
asawyer Avatar asked Feb 21 '11 21:02

asawyer


People also ask

How do I convert DateTime to short date?

The DateTime. ToShortDateString() method in C# is used to convert the value of the current DateTime object to its equivalent short date string representation.

What is short date string?

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo. ShortDatePattern property. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.

How do I format a date string?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.

What is DateTime string Z?

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).


2 Answers

Try decorating your view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateRequested { get; set; };

and in your view use the Html.EditorFor helper:

<div class="editor-field">
    <%: Html.EditorFor(model => model.DateRequested) %>
    <%: Html.ValidationMessageFor(model => model.DateRequested) %>
</div>

or if you insist on using textbox helper (don't know why would you but anyway here's how):

<div class="editor-field">
    <%: Html.TextBox("DateRequested", Model.DateRequested.ToShortDateString()) %>
    <%: Html.ValidationMessageFor(model => model.DateRequested) %>
</div>
like image 90
Darin Dimitrov Avatar answered Oct 09 '22 12:10

Darin Dimitrov


If you want to stick with an html helper method, try this:

public static MvcHtmlString TextBoxDateTime<TModel>(this HtmlHelper<TModel> helper,
             Expression<Func<TModel, DateTime>> expression, int tabIndex = 1)
    {
        var meta = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        var propertyName = ExpressionHelper.GetExpressionText(expression);

        var input = new TagBuilder("input");
        input.MergeAttribute("id",
                             helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName)));
        input.MergeAttribute("name",
                             helper.AttributeEncode(
                                 helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName)));
        input.MergeAttribute("value", ((DateTime)meta.Model).ToShortDateString());
        input.MergeAttribute("type", "text");
        input.MergeAttribute("class", "text cal");
        input.MergeAttribute("tabindex", tabIndex.ToString());
        input.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), meta));
        return MvcHtmlString.Create(input.ToString());
    }
like image 35
Donger Avatar answered Oct 09 '22 12:10

Donger