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... 透视总结!wpk模拟器,wpk辅助软件-竟然是真的有辅助技巧(哔哩哔哩)1、进入游戏-大厅左侧-新手...
透视有挂!wepoker有辅助... 透视有挂!wepoker有辅助功能吗,wepoker智能辅助插件-好像存在有辅助教程(哔哩哔哩)1、...
透视开挂!pokemmo辅助官... 透视开挂!pokemmo辅助官网,cloudpoker怎么开挂-果然有辅助教程(哔哩哔哩)1、下载好...
透视分享!wepoker破解器... 透视分享!wepoker破解器有用吗,wepoker私人局辅助挂-好像是真的有辅助软件(哔哩哔哩)1...
透视辅助!pokemomo辅助... 透视辅助!pokemomo辅助工具,pokernow辅助控制-竟然是真的有辅助软件(哔哩哔哩)1、下...
透视开挂!德普之星透视辅助软件... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
透视普及!wpk辅助是什么,w... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视曝光!wpk辅助器,wpk... 透视曝光!wpk辅助器,wpk软件是真的吗-切实有辅助技巧(哔哩哔哩)透视方法中分为三种模型:靠谱、...
透视普及!wepokerplu... 透视普及!wepokerplus万能挂,wepoker透视脚本免费下载-竟然真的是有辅助软件(哔哩哔...
透视推荐!wepoker辅助器... 透视推荐!wepoker辅助器最新版本更新内容,wepoker科技辅助器-本来是有辅助工具(哔哩哔哩...