日期格式绑定(ASP.NET MVC) [英] Format Date On Binding (ASP.NET MVC)
问题描述
在我的ASP.net MVC应用程序我有一个看起来像这样一个观点:
In my ASP.net MVC app I have a view that looks like this:
...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...
我使用的是 ModelBinder的
到后期绑定到我的模型(由于属性是的DateTime
类型) 。问题是,当我把01/01/2009到文本框中,及后不验证(由于其他数据正在输入错误)。粘结剂与日期的和时间01/01/2009 00:00:00 重新填充它。
I am using a ModelBinder
to bind the post to my model (the due property is of DateTime
type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00".
有没有办法告诉粘结剂以正确格式化的日期(即 ToShortDateString()
)?
Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString()
)?
推荐答案
我只是碰到这个非常简单和优雅的解决方案来了,MVC 2可供选择:
I just came across this very simple and elegant solution, available in MVC 2:
<一个href=\"http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx\">http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx
基本上,如果你正在使用的MVC 2.0,使用您的看法如下。
Basically if you are using MVC 2.0, use the following in your view.
<%=Html.LabelFor(m => m.due) %>
<%=Html.EditorFor(m => m.due)%>
然后创建/浏览次数局部视图/共享/ EditorTemplates,叫DateTime.ascx
then create a partial view in /Views/Shared/EditorTemplates, called 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&LT;>被称为就会找到匹配的编辑模板
When the EditorFor<> is called it will find a matching Editor Template.
这篇关于日期格式绑定(ASP.NET MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!