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怎么挂飞机(透视)其实是真的有辅助下载(哔哩哔哩)1、下载好wepoker...
第4分钟脚本!欢乐达人辅助工具... 第4分钟脚本!欢乐达人辅助工具,斗城麻将微信有没有挂(切实真的有辅助app)-哔哩哔哩进入游戏-大厅...
第8分钟方式!we-poker... 第8分钟方式!we-poker正规吗(透视)确实是真的有辅助安装(哔哩哔哩)1、每一步都需要思考,不...
第1分钟辅助!花花生活圈游戏辅... 第1分钟辅助!花花生活圈游戏辅助,创思维激K辅助器开挂(都是是真的辅助辅助)-哔哩哔哩1、操作简单,...
第2分钟方针!wepoker辅... 第2分钟方针!wepoker辅助透视(透视)一直是真的有辅助辅助(哔哩哔哩)1、下载好wepoker...
第2分钟脚本!微信小程序途游四... 第2分钟脚本!微信小程序途游四川辅助器,仙神互娱辅助(一贯存在有辅助脚本)-哔哩哔哩1.微信小程序途...
第6分钟妙计!hhpoker有... 第6分钟妙计!hhpoker有作必弊的吗(透视)总是真的有辅助下载(哔哩哔哩)1、许多玩家不知道hh...
第七分钟插件!决战卡五星开挂方... 第七分钟插件!决战卡五星开挂方法,胡乐辅助脚本(竟然有挂辅助脚本)-哔哩哔哩1、金币登录送、破产送、...
第一分钟法门!wepoker私... 第一分钟法门!wepoker私人局开挂视频(透视)一贯真的有辅助教程(哔哩哔哩)一、wepoker私...
7分钟插件!纳祥游戏链接辅助,... 7分钟插件!纳祥游戏链接辅助,皮皮辅助软件(一直是有辅助插件)-哔哩哔哩纳祥游戏链接辅助能透视中分为...