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系统是否存在作必弊行为,wepoker买脚本靠谱吗,绝活教程(有挂教程)-哔哩哔哩1...
关于透视!hardrock作必... 关于透视!hardrock作必弊!确实一直总是有辅助app(有挂解惑)-哔哩哔哩运hardrock作...
总结透视!wejoker透视方... 总结透视!wejoker透视方法,德普之星透视辅助软件,策略教程(有挂方式)-哔哩哔哩1、每一步都需...
分享透视!哈糖大菠萝助手!果然... 分享透视!哈糖大菠萝助手!果然真的是有辅助教程(有挂规律)-哔哩哔哩1、玩家可以在哈糖大菠萝助手透视...
总结透视!pokemmo手机脚... 总结透视!pokemmo手机脚本辅助器,wepoker怎么增加运气,方式教程(有挂助手)-哔哩哔哩;...
解密透视!约局吧德州可以透视吗... 解密透视!约局吧德州可以透视吗!确实真的是有辅助工具(有挂讲解)-哔哩哔哩亲,关键说明,约局吧德州可...
普及透视!we-poker辅助... 普及透视!we-poker辅助软件教程,aapoker能控制牌吗,模块教程(有挂攻略)-哔哩哔哩1、...
科普透视!pokemomo辅助... 科普透视!pokemomo辅助软件!好像存在有辅助神器(讲解有挂)-哔哩哔哩1、pokemomo辅助...
专业透视!wpk插件,wepo... 专业透视!wpk插件,wepoker透视挂底牌,法子教程(有挂教学)-哔哩哔哩1、完成wepoker...
教你透视!福建大菠萝万能辅助器... 教你透视!福建大菠萝万能辅助器!好像有辅助工具(有挂详细)-哔哩哔哩1、上手简单,内置详细流程视频教...