MVC ModelMetaData 属性和格式化日期的问题
我试图弄清楚如何使用 MVC3 RC2 和用 DataAnnotations 装饰的模型来格式化日期。
这是我的模型...
public class Model
{
[Display(Name = "Date of Birth")]
[DisplayFormat(@DataFormatString = "MM/dd/yyyy")]
public DateTime DateOfBirth { get; set; }
}
这是我的控制器...
public class IndexController : Controller
{
public ActionResult Index()
{
return View( new Model() {DateOfBirth = DateTime.Now});
}
}
这是我的视图...
@model MvcApplication6.Models.Model
@Html.LabelFor(m=>m.DateOfBirth)
@Html.TextBoxFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth)
当我运行该站点时,对于两个控件,页面显示一个文本框,其中包含字符串中的时间,而我想要的只是日期(由模型中的装饰属性指定)。
我使用了 Brad Wilson 的文章 在此模式的 ModelMetaData 上。
我做错了什么很明显吗?
I am trying to figure out how to format a date using MVC3 RC2 and a model decorated with DataAnnotations.
This is my model...
public class Model
{
[Display(Name = "Date of Birth")]
[DisplayFormat(@DataFormatString = "MM/dd/yyyy")]
public DateTime DateOfBirth { get; set; }
}
This is my controller...
public class IndexController : Controller
{
public ActionResult Index()
{
return View( new Model() {DateOfBirth = DateTime.Now});
}
}
This is my view...
@model MvcApplication6.Models.Model
@Html.LabelFor(m=>m.DateOfBirth)
@Html.TextBoxFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth)
When I run the site, for both controls, the page displays a textbox with the time included in the string, when all I want is the date (as specified by the decorated property in the model).
I used Brad Wilson's article on ModelMetaData for this pattern.
Is it obvious what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样做:
Do this:
事实上,我认为这里的问题与 DefaultModelBinder 没有以正确的方式处理日期时间这一事实有关(这意味着我们无法将前端字段绑定到 DateTime 部分) ,就像我们过去在其他[咳 CastleMonorail 咳] MVC 框架中所做的那样。
我创建了一个自定义模型绑定器来解决这个问题。但是 Scott Hanselman 在此处做了类似的事情,所以我想你可以使用他的解决方案。
当然,您可以通过属性来处理这种情况,但这意味着您需要在所有 DateTime 字段中指定特殊格式。这并不能解决另一个问题:有时我们需要仅在前端有一个用于日期部分的字段和另一个用于时间部分的字段,并在后端保留一个日期时间字段。该模型活页夹解决方案正是实现了这一点。
In fact I believe that the problem here is related to the fact that the
DefaultModelBinder
does not deal with datetimes in a proper way (meaning that we cannot bind a front-end field to a DateTime partial, like we used to do in others [cough CastleMonorail cough] MVC frameworks).I've created a custom model binder exactly to deal with that issue. But Scott Hanselman has done something similar here, so I guess you can just use his solution.
Of course, you may deal with this situation through attributes, but that means that you'll need to specify that special formatting in all DateTime fields. And that will not solve another problem: sometimes we need to have one field for the date part and another for the time part only in the front-end, and keep a single datetime field in the backend. This model binder solution allows exactly that.