MVC ModelMetaData属性和格式化Date的问题

时间:2011-01-07 19:32:34

标签: asp.net-mvc asp.net-mvc-3 datetime data-annotations 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)

当我运行网站时,对于两个控件,页面显示一个文本框,其中包含时间字符串,当我想要的只是日期时(由模型中的装饰属性指定)。

我在ModelMetaData上使用Brad Wilson的article来表示这种模式。

我做错了很明显吗?

2 个答案:

答案 0 :(得分:7)

这样做:

[DisplayName("Date of Birth")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DateOfBirth { get; set; }

答案 1 :(得分:0)

实际上我认为这里的问题与DefaultModelBinder没有正确处理日期时间这一事实有关(意味着我们无法将前端字段绑定到DateTime partial ,就像我们以前在其他人[咳嗽 CastleMonorail 咳嗽] MVC框架中所做的那样。)

我已经创建了一个自定义模型绑定器来处理这个问题。但是Scott Hanselman做了类似here的事情,所以我想你可以使用他的解决方案。

当然,您可以通过属性处理这种情况,但这意味着您需要在所有 DateTime字段中指定特殊格式。这不会解决另一个问题:有时我们需要为日期部分设置一个字段,而在时间部分仅在前端设置另一个字段,并在后端保留一个日期时间字段。这种模型粘合剂解决方案恰好允许这样做。

相关问题