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

相关内容

热门资讯

5分钟安装!微乐小程序黑科技,... 5分钟安装!微乐小程序黑科技,微乐手游脚本辅助(开挂)一贯有挂(2026)在进入微乐小程序黑科技软件...
透视安装!微乐小程序黑科技,微... 透视安装!微乐小程序黑科技,微乐小程序微乐房间怎么开挂(透视)一直是真的挂(哔哩哔哩);1)微乐小程...
第9分钟下载!微乐小程序免费黑... 第9分钟下载!微乐小程序免费黑科技,小程序跑得快的技巧(开挂)切实存在有挂(2026)在进入微乐小程...
透视黑科技!微乐小程序黑科技,... 透视黑科技!微乐小程序黑科技,微信微乐游戏辅助脚本(透视)果然是有挂(哔哩哔哩)1、该软件可以轻松地...
第十分钟神器!微乐小程序黑科技... 您好,微乐小程序黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
透视教程!微乐小程序黑科技,微... 透视教程!微乐小程序黑科技,微乐小程序脚本入口(透视)确实是真的挂(哔哩哔哩)1、这是跨平台的微乐小...
第二分钟辅助!微乐小程序黑科技... 第二分钟辅助!微乐小程序黑科技,微乐游戏小程序脚本(开挂)本来有挂(2026)在进入微乐小程序黑科技...
黑科技技巧!微乐小程序黑科技,... 黑科技技巧!微乐小程序黑科技,微乐自建房辅助工具下载入口在哪(透视)果然是真的挂(哔哩哔哩)黑科技技...
七分钟插件!微乐小程序免费黑科... 七分钟插件!微乐小程序免费黑科技,微乐小程序黑科技免费知乎(开挂)原来存在有挂(2026)1、上手简...
透视能赢!微乐小程序免费黑科技... 透视能赢!微乐小程序免费黑科技,微乐手游脚本辅助(透视)真是有挂(哔哩哔哩)1.微乐小程序免费黑科技...