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分钟方案!wepoker可以... 1分钟方案!wepoker可以开透视吗(透视)竟然存在有辅助下载(哔哩哔哩)1、1分钟方案!wepo...
两分钟步骤!hhpoker有辅... 两分钟步骤!hhpoker有辅助吗(透视)一直存在有辅助安装(哔哩哔哩)1、用户打开应用后不用登录就...
第九分钟窍门!wepoker辅... 第九分钟窍门!wepoker辅助软件价格(透视)都是存在有辅助辅助(哔哩哔哩)1、玩家可以在wepo...
第七分钟手册!德州透视hhpo... 第七分钟手册!德州透视hhpoker(透视)本来是真的有辅助插件(哔哩哔哩)1、用户打开应用后不用登...
六分钟攻略!wepoker代打... 六分钟攻略!wepoker代打辅助(透视)本来是有辅助辅助(哔哩哔哩)1、wepoker代打辅助辅助...
五分钟办法!wepoker怎么... 五分钟办法!wepoker怎么获得好牌(透视)确实真的有辅助下载(哔哩哔哩)一、wepoker怎么获...
第3分钟策略!wepoker辅... 第3分钟策略!wepoker辅助器怎么弄(透视)一直有辅助下载(哔哩哔哩)1、下载好wepoker辅...
第4分钟项目!wepoker透... 第4分钟项目!wepoker透视脚本苹果版(透视)一贯存在有辅助安装(哔哩哔哩)亲,关键说明,wep...
第1分钟项目!wepoker私... 第1分钟项目!wepoker私人局透视插件(透视)好像真的有辅助安装(哔哩哔哩)暗藏猫腻,小编详细说...
8分钟机巧!hhpoker底牌... 8分钟机巧!hhpoker底牌透视脚本(透视)切实真的是有辅助神器(哔哩哔哩)hhpoker底牌透视...