问题
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?
回答1:
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>
回答2:
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());
}
来源:https://stackoverflow.com/questions/5071631/display-datetime-model-property-as-short-date-time-string