Display datetime model property as Short date time string

a 夏天 提交于 2019-12-03 13:07:23

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>
Donger

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());
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!