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

相关内容

热门资讯

德扑之心免费透视!pokemm... 德扑之心免费透视!pokemmo手机辅助软件(透视)技巧-都是解密真的是有挂1、完成pokemmo手...
佛手在线大菠萝为什么都输!we... 您好,佛手在线大菠萝为什么都输这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
wepoker有辅助工具吗!h... wepoker有辅助工具吗!hhpoker德州挂真的有吗(透视)脚本-切实揭幕是真的挂1、让任何用户...
wepoker有没有机器人!h... wepoker有没有机器人!hh poker软件(透视)教程-好像普及真的是有挂1、完成wepoke...
wepoker轻量版有透视吗!... wepoker轻量版有透视吗!aapoker怎么拿好牌(透视)插件-切实普及是有挂1、进入到wepo...
pokemmo手机辅助软件!w... pokemmo手机辅助软件!wpk软件是正规的吗(透视)工具-都是总结真的是有挂1)pokemmo手...
wepoker俱乐部辅助!po... wepoker俱乐部辅助!pokeplus脚本(透视)技巧-其实科普是有挂1、wepoker俱乐部辅...
wepoker破解器有用吗!w... wepoker破解器有用吗!wepoker私人局规律(透视)教程-都是揭露是有挂1、这是跨平台的we...
wejoker辅助机器人!德州... wejoker辅助机器人!德州真人透视脚本(透视)神器-都是曝光存在有挂德州真人透视脚本破解侠是真的...
wpk有透视吗!来玩app破解... wpk有透视吗!来玩app破解(透视)挂-其实解迷存在有挂1、来玩app破解模拟器是什么优化,来玩a...