日期格式绑定(ASP.NET MVC) [英] Format Date On Binding (ASP.NET MVC)

查看:138
本文介绍了日期格式绑定(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屋!

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