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

相关内容

热门资讯

目前来看!pokemmo脚本,... 目前来看!pokemmo脚本,福建天天开心攻略,一贯是真的有辅助技巧(哔哩哔哩)1、下载好福建天天开...
随着!wepoker透视破解版... 随着!wepoker透视破解版,牛财神插件,确实存在有辅助神器(哔哩哔哩)一、牛财神插件可以开透视的...
突发!hhpoker作必弊实战... 突发!hhpoker作必弊实战视频,拱趴大菠萝怎么开挂,原来有辅助app(哔哩哔哩)hhpoker作...
此事引发广泛关注!wpk辅助插... 此事引发广泛关注!wpk辅助插件,神兽h5平台反杀,好像真的是有辅助技巧(哔哩哔哩)1、超多福利:超...
据文件显示!wepoker有没... 据文件显示!wepoker有没有挂,微信牵手跑辅助,切实是真的有辅助攻略(哔哩哔哩)1、全新机制【微...
截至目前!德普之星透视辅助,杭... 截至目前!德普之星透视辅助,杭州都莱辅助,总是有辅助神器(哔哩哔哩)1、下载好杭州都莱辅助脚本下载之...
连日来!wepoker怎么拿到... 连日来!wepoker怎么拿到好牌,邳州友友辅助,一贯真的有辅助工具(哔哩哔哩)1、连日来!wepo...
据悉!wepoker有没有挂,... 您好,上饶辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款...
此事引发网友热议!aapoke... 此事引发网友热议!aapoker安装包怎么使用,皇豪互众智能辅助器,本来有辅助插件(哔哩哔哩);1、...
反观!wepoker科技辅助器... 反观!wepoker科技辅助器,青橙竞技游戏辅助,其实存在有辅助app(哔哩哔哩)1、打开软件启动之...