c# - 回发后的模型绑定(bind)将 DateTime 属性设置为 NULL

标签 c# asp.net-mvc model-binding datetime-format

我的 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/

相关文章:

asp.net-mvc - 确保 Controller 在 web api 中有一个无参数的公共(public)构造函数?

c# - 我的 workspace setting.json for unity on VSCode 表示 'end of file' 预期在 files.exclude 之后

c# - 如何正确地在 If 语句中进行等价测试?

c# - 正则表达式捕获具有 1 到 5 个序数的组

c# - 用 C# 读取带有注释的 MS Word 文件

asp.net-mvc - 排序逻辑应该放在模型、 View 还是 Controller 中?

javascript - 实现 Jquery 日期时间选择器

asp.net-mvc - 模型绑定(bind)时查找 View 模型属性上的自定义属性

c# - 如何禁用特定 ASP.NET Core 5.0 Web API 操作的自动模型绑定(bind)?

c# - 如何扩展 ComplexTypeModelBinder