ASPNETMVC无法接受空的日期时间(NullDatetime)
创始人
2024-09-20 09:31:32
0

在 ASP NET MVC 中,当从视图中传递 DateTime 属性时,如果该属性为 null,就会抛出异常。可以通过以下两种方式解决:

  1. 将 DateTime 属性声明为可空类型,如下所示:

public class MyClass { public DateTime? MyDateTime { get; set; } }

在视图中,如果该属性为空,则可以这样进行检查:

@if (Model.MyDateTime.HasValue) { // DateTime 不为 null 的操作 } else { // DateTime 为 null 的操作 }

  1. 使用自定义模型绑定器

在自定义模型绑定器中,我们可以重写默认的行为,使其能够接受空值。以下是示例代码:

public class NullableDateTimeModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (valueProviderResult == null || string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
    {
        return null;
    }

    DateTime.TryParse(valueProviderResult.AttemptedValue, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateValue);

    return dateValue;
}

}

然后,在全局.asax.cs 中注册模型绑定器:

protected void Application_Start() { // ... ModelBinders.Binders.Add(typeof(DateTime?), new NullableDateTimeModelBinder()); }

在视图中,将 DateTime 属性声明为可空类型即可:

public class MyClass { public DateTime? MyDateTime { get; set; } }

相关内容

热门资讯

透视项目!wepoker私局代... 透视项目!wepoker私局代打,WePoKer线上一直真的有脚本,第2分钟教程(有挂规律)在进入w...
透视教程书!aapoker辅助... 透视教程书!aapoker辅助软件合法吗,AApoker软件原来是真的有开挂,3分钟教程(确实有挂)...
透视演示!如何下载wpk透视版... 透视演示!如何下载wpk透视版,WPK安卓一贯存在有工具,第六分钟教程(有挂详细)1、上手简单,内置...
透视举措!aapoker俱乐部... 透视举措!aapoker俱乐部靠谱吗,AApoker发牌逻辑其实是有神器,六分钟教程(有挂技术)1、...
透视步骤!聚星ai辅助工具激活... 透视步骤!聚星ai辅助工具激活码,WePoKer透视底牌一直有工具,第6分钟教程(有挂方法)1、聚星...
透视妙招!德州hhpoker是... 透视妙招!德州hhpoker是真的吗,HHpoker开挂本来是真的有教程,九分钟教程(确实有挂)1、...
透视方式!德普之星透视免费,德... 透视方式!德普之星透视免费,德普之星埋牌原来真的是有透视,第三分钟教程(有挂秘籍)1、每一步都需要思...
透视大纲!德普之星有透视辅助吗... 透视大纲!德普之星有透视辅助吗,德普之星介绍竟然真的是有开挂,第九分钟教程(有挂教程)1、完成德普之...
透视模块!aapoker怎么设... 透视模块!aapoker怎么设置提高好牌几率,AApoker工具切实有脚本,第5分钟教程(确实有挂)...
透视方式!wpk刷入池率脚本,... 透视方式!wpk刷入池率脚本,WPK链接好像存在有辅助,第八分钟教程(有挂猫腻)1)wpk刷入池率脚...