加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 使用ViewModel和html类属性设置的日期格式输入

发布时间:2020-12-16 03:37:30 所属栏目:asp.Net 来源:网络整理
导读:我正在使用asp.net mvc3中的razor视图引擎. 现在,我需要一个DateTime的输入,它应该以固定的格式显示值(比如dd-MMM-yyyy).所以我可以这样做: [DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd-MMM-yyyy}")]public DateTime StartDate
我正在使用asp.net mvc3中的razor视图引擎.

现在,我需要一个DateTime的输入,它应该以固定的格式显示值(比如dd-MMM-yyyy).所以我可以这样做:

[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }

在视图中:

@Html.EditorFor(model => model.StartDate)

但我需要在输入中添加一个类.我认为在EditorFor中是不可能的.
所以我可以使用

@Html.TextBoxFor(model => model.StartDate,new { @class = "Date" })

但是在这种情况下显示格式不起作用.

模型可以为null.所以,

@Html.TextBox("StartDate",string.Format("{0:dd-MMM-yyyy}",Model.StartDate))

将抛出NullReferenceException.

解决方法

奥菲莉亚的方式是我的更快版本.但是,如果您的应用程序中有一些日期字段,这种方式很有用.所以这就是我喜欢的方式:

– >在您的解决方案资源管理器中,在Shared中创建一个名为“EditorTemplates”的文件夹

– >在那里,添加一个新的(非强类型)局部视图.称之为“DateTime”.

– >打开此视图,并删除其中的任何代码,并在其中抛出以下代码:

@model System.DateTime
    @Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue,new { @class = "date" /* + any other html attributes you want */ })

– >在您的ViewModel中,您的日期字段应如下所示:

[Display(Name = "My Date:"),DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}",ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }

– >在主视图和任何想要使用日期字段的视图中,您可以在属性上使用EditorFor,如下所示:

@Html.EditorFor(m => m.MyDate)

您可以在控制器中初始化日期字段,或在viewmodel的构造函数中设置默认日期.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读