在我的 ASP.net MVC 应用程序中,我有一个如下所示的视图:
...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...
我正在使用一个ModelBinder
将帖子绑定到我的模型(应有的属性是DateTime
类型)。问题是当我将“01/01/2009”放入文本框中时,该帖子未验证(由于其他数据输入不正确)。活页夹用日期重新填充它and time“2009 年 1 月 1 日00:00:00".
有什么方法可以告诉活页夹正确格式化日期(即ToShortDateString()
)?
我刚刚遇到了这个非常简单而优雅的解决方案,可在 MVC 2 中使用:
Link https://web.archive.org/web/20200804032742/http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx
基本上,如果您使用的是 MVC 2.0,请在您的视图中使用以下内容。
<%=Html.LabelFor(m => m.due) %>
<%=Html.EditorFor(m => m.due)%>
然后在 /Views/Shared/EditorTemplates 中创建一个部分视图,名为 DateTime.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %>
当调用 EditorFor 时,它将找到匹配的编辑器模板。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)