问题描述
我是新与MVC2,和我有一个格式化的问题。我有一个DateTime属性,我想用短日期时间显示我的员工的模型。
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>
2号线将引发此异常:
Line 2 throws this exception:
模板只能与现场使用
访问属性访问,
一维数组索引,或者
单参数自定义索引
前pressions。
什么是处理MVC格式的正确方法是什么?
What is the correct way to handle formatting in mvc?
推荐答案
尝试使用<$c$c>[DisplayFormat]$c$c>属性:
Try decorating your view model property with the [DisplayFormat]
attribute:
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateRequested { get; set; };
和在您的视图中使用 Html.EditorFor
助手:
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>
这篇关于显示日期时间model属性短日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!