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

相关内容

热门资讯

透视讲解!红龙poker脚本,... 1、透视讲解!红龙poker脚本,德普之星怎么作弊,大神推荐(有挂教学)。2、德普之星怎么作弊透视辅...
透视模拟器!wepoker作弊... 透视模拟器!wepoker作弊辅助,aapoker透视脚本,安装教程(最初真的是有挂);亲真的是有正...
透视辅助!德普之星辅助功能如何... 您好,德普之星辅助功能如何打开这款游戏可以开挂的,确实是有挂的,需要了解加Q群【1067239143...
透视存在!wepoker透视脚... 大家肯定在之前wepoker透视脚本免费下载或者wepoker透视脚本免费下载中玩过透视存在!wep...
透视数据!智星德州菠萝插件官网... 1、透视数据!智星德州菠萝插件官网,wpk透视辅助方法,普及知识(有挂规律);该软件可以轻松地帮助玩...
透视计算!wpk有没有脚本,w... 透视计算!wpk有没有脚本,wepoker辅助透视软件,详细教程(总是存在有挂)1、让任何用户在无需...
透视透视!hhpoker免费透... 透视透视!hhpoker免费透视脚本,德普之星怎么作弊,大神普及(有挂教程)1、每一步都需要思考,不...
透视科技!wepoker透视,... 大家肯定在之前wepoker透视或者wepoker透视中玩过透视科技!wepoker透视,wepok...
透视工具!wpk脚本下载,aa... 透视工具!wpk脚本下载,aapoker辅助功能,终于知道(有挂教学)(1)透视工具!wpk脚本下载...
透视软件!德普之星有没有挂,约... 透视软件!德普之星有没有挂,约局吧辅助器,必赢方法(确实有挂)需要回顾用户提供的搜索结果,比如,提到...