显示日期时间model属性短日期时间字符串 [英] Display datetime model property as Short date time string

查看:143
本文介绍了显示日期时间model属性短日期时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新与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。

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

什么是处理MVC格式的正确方法是什么?

What is the correct way to handle formatting in mvc?

推荐答案

尝试使用<一个装饰您的视图模型属性href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx\"><$c$c>[DisplayFormat]属性:

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属性短日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆