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分钟透视!钱塘13水挂件,随... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
关于透视"wepok... 关于透视"wepoker真能买到挂吗"开挂(透视)辅助挂(必备辅助推荐技巧教程)关于透视"wepok...
2分钟开挂!决战十水三余音,永... 2分钟开挂!决战十水三余音,永盛联盟辅助脚本(一分钟了解开挂辅助工具) 了解更多开挂安装加(1367...
必看透视"wepok... 必看透视"wepoker私人局怎么设置抽水"开挂(透视)辅助插件(玩家必看攻略解说技巧)必看透视"w...
七分钟辅助!新道游修改器,we... 七分钟辅助!新道游修改器,werplan脚本(透视神器开挂辅助安装);无需打开直接搜索加(薇:136...
细节透视"微扑克发牌... 细节透视"微扑克发牌机制详解"开挂(透视)辅助插件(重大消息辅助教程)细节透视"微扑克发牌机制详解"...
第九分钟透视!川南休闲辅助,新... 第九分钟透视!川南休闲辅助,新九哥辅助(透视挂透视开挂辅助下载)>>您好:软件加136704302中...
关于透视"wepok... 关于透视"wepoker透视辅助挂的游戏特色"开挂(透视)辅助脚本(玩家必看科普实用技巧)关于透视"...
第三分钟开挂!辽宁心悦游戏辅助... 辽宁心悦游戏辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微...
四分钟辅助!哈糖大菠萝辅助,三... 四分钟辅助!哈糖大菠萝辅助,三江互娱辅助(透视智能ai开挂辅助下载)《详细加薇136704302咨询...