我的 ASP.NET MVC View 模型具有日期时间属性,例如:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "yyyyMMdd")]
public DateTime DateOfBirth { get; set; }
我的 Controller 操作有:
[HttpPost]
public JsonResult OnCreate(MyViewModel model)
{
}
我的属性确实已绑定(bind),除了日期时间属性。
我输入的日期如下:
19500125
这是 1950 年 1 月 25 日,我的日期格式设置为:yyyyMMdd
如果我执行以下操作,则此操作有效:
DateTime dateOfBirth;
if (DateTime.TryParseExact(Request["User.dateOfBirth"], "yyyyMMdd", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateOfBirth))
{
model.User.DateOfBirth = dateOfBirth;
}
但是上面没有使用内置绑定(bind),并且不是正确的处理方法。
有任何线索说明为什么日期时间的绑定(bind)不起作用吗?
最佳答案
Any clues why the binding for datetime isnt' working?
它正在按预期工作。默认的 ModelBinder 仅绑定(bind)到特定的日期时间格式。我认为问题在于您假设 DisplayFormatAttribute 对 ModelBinder 有一些影响。正如该属性所述,它仅适用于显示格式,不适用于模型绑定(bind)。如果您有自定义日期时间格式(您确实这样做),那么您需要编写 custom DateTime model binder绑定(bind)它。
关于c# - 回发后的模型绑定(bind)将 DateTime 属性设置为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25628076/