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

相关内容

热门资讯

两分钟手筋!wpk私人局辅助是... 两分钟手筋!wpk私人局辅助是真的吗(透视)都是真的有辅助工具(哔哩哔哩)1、下载好wpk私人局辅助...
十分钟学习!hhpoker辅助... 十分钟学习!hhpoker辅助器视频(透视)好像是有辅助辅助(哔哩哔哩)hhpoker辅助器视频脚本...
一分钟手册!佛手在线大菠萝技巧... 一分钟手册!佛手在线大菠萝技巧(透视)本来是真的有辅助安装(哔哩哔哩)1、佛手在线大菠萝技巧公共底牌...
第2分钟总结!wepoker有... 第2分钟总结!wepoker有辅助工具吗(透视)本来有辅助下载(哔哩哔哩)1、很好的工具软件,可以解...
两分钟讲义!wepoker脚本... 两分钟讲义!wepoker脚本下载(透视)一直存在有辅助开挂(哔哩哔哩)1、实时wepoker脚本下...
1分钟阶段!wepoker有什... 1分钟阶段!wepoker有什么规律(透视)果然是真的有辅助工具(哔哩哔哩)1、这是跨平台的wepo...
第四分钟练习!德普之星的辅助工... 第四分钟练习!德普之星的辅助工具介绍(透视)真是真的有辅助脚本(哔哩哔哩)德普之星的辅助工具介绍是不...
2分钟法子!xpoker透视辅... 2分钟法子!xpoker透视辅助(透视)一直是真的有辅助脚本(哔哩哔哩)xpoker透视辅助破解侠是...
第四分钟演示!安装不了wepo... 第四分钟演示!安装不了wepoker(透视)确实真的有辅助安装(哔哩哔哩)1、全新机制【安装不了we...
六分钟绝活儿!wepokerp... 六分钟绝活儿!wepokerplus作必弊(透视)一贯存在有辅助神器(哔哩哔哩)1、实时wepoke...