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; } }

相关内容

热门资讯

微信小程序黑科技免费!微乐小程... 微信小程序黑科技免费!微乐小程序辅助器出租(开挂)方法-原来专业是有挂辅助器是一种具有地方特色的麻将...
微乐小程序黑科技!微乐广西小程... 微乐小程序黑科技!微乐广西小程序(开挂)技巧-一直分享有挂1、这是跨平台的轻量版有透视,在线的操作超...
微乐小程序存在有挂!微乐降序自... 微乐小程序存在有挂!微乐降序自建房辅助app(开挂)技巧-总是开挂真的是有挂1、游戏颠覆性的策略玩法...
微信小程序黑科技免费!微乐家乡... 微信小程序黑科技免费!微乐家乡自建房辅助app(开挂)神器-真是教你存在有挂1、破解器简单,机器人操...
微乐小程序透视辅助!微信小程序... 微乐小程序透视辅助!微信小程序游戏充值破解(开挂)工具-原来必备有挂1、有没有辅助教程、有透视吗等服...
微乐小程序黑科技!微乐自建房脚... 微乐小程序黑科技!微乐自建房脚本免费下载入口(开挂)插件-果然有挂存在有挂1、有没有辅助教程、有透视...
微乐小程序透视挂!微乐河南家乡... 微乐小程序透视挂!微乐河南家乡麻将辅助脚本(开挂)app-其实教你是有挂1、不需要AI权限,帮助你快...
微乐小程序存在有挂!微信小程序... 微乐小程序存在有挂!微信小程序游戏充值破解(开挂)软件-本来推荐是真的挂1、下载好脚本下载之后点击打...
微乐小程序透视辅助!微乐小程序... 微乐小程序透视辅助!微乐小程序自建房插件免费(开挂)插件-切实解密是真的挂;能透视中分为三种模型:模...
微信小程序微乐破解器!微乐自建... 微信小程序微乐破解器!微乐自建房插件免费软件(开挂)方法-好像解迷存在有挂1、有没有辅助教程、有透视...