代码改变世界

勤于思考:Asp.Net MVC Html.TextBoxFor日期格式化

2013-05-03 15:47  薛凯凯圆滚滚  阅读(5441)  评论(3编辑  收藏  举报

先看例子 本来使用实体结果出来的日期 (2013/05/03 00:11:33)

但是我的本意并不是想要这样的格式,所以在属性后面加上ToString("yyyy-MM-dd")

结果报出 "模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式。"

@Html.TextBoxFor(model => model.StartDate.ToString("yyyy-MM-dd"), new { @class = "Wdate searchText",  @readonly = "readonly", @onfocus = "WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd'})" })<span class="fRed">&nbsp;*</span>

解决方案

@Html.TextBoxFor(model => model.StartDate, new { @class = "Wdate searchText", Value = String.Format("{0:yyyy-MM-dd}", Model.StartDate), @readonly = "readonly", @onfocus = "WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd'})" })<span class="fRed">&nbsp;*</span>

 或者

@Html.TextBoxFor(model => model.EndDate, new { @class = "Wdate searchText",Value = Model.EndDate.ToString("yyyy-MM-dd"), @readonly = "readonly", @onfocus = "WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd'})" })<span class="fRed">&nbsp;*</span>

 

当然如果使用 模板注解的话也可以用另一种方式

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public System.DateTime StartDate
{
    get { return _startDate; }
    set { _startDate = value; }
}

使用的话就这样

@Html.EditorFor(model => model.StartDate, new { @class = "Wdate searchText",  @readonly = "readonly", @onfocus = "WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd'})" })<span class="fRed">&nbsp;*</span>