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

相关内容

热门资讯

透视好牌!拱趴大菠萝机器人,p... 透视好牌!拱趴大菠萝机器人,pokemmo免费脚本(果然有挂);一、拱趴大菠萝机器人软件透明挂的定义...
aapoker辅助工具存在!a... aapoker辅助工具存在!aapoker有猫腻吗,(aapokEr)一直存在有挂,详细教程(有挂详...
透视透视!德州透视脚本,竞技联... 透视透视!德州透视脚本,竞技联盟破解版最新版(好像有挂);1、操作简单,无需注册,只需要使用手机进行...
aapoker辅助工具存在!a... aapoker辅助工具存在!aapoker有什么规律吗,(AAPOKEr)竟然是有挂,详细教程(有挂...
透视美元局!拱趴大菠萝挂哪里,... 透视美元局!拱趴大菠萝挂哪里,pokemomo辅助工具(竟然存在有挂);1、拱趴大菠萝挂哪里ai机器...
aapoker有挂!德州aa辅... aapoker有挂!德州aa辅助,(Aapoker)原来有挂,详细教程(有挂总结)是一款可以让一直输...
aapoker辅助工具!aa扑... 这是一款非常优秀的aapoker辅助工具 ia辅助检测软件,能够让你了解到aapoker辅助工具中牌...
透视辅助!哈糖大菠萝怎么开挂,... 透视辅助!哈糖大菠萝怎么开挂,epoker有透视吗(好像真的有挂);1、在哈糖大菠萝怎么开挂ai机器...
透视代打!哈糖大菠萝软件下载,... 透视代打!哈糖大菠萝软件下载,菠萝德普辅助器免费版在哪里(果然是有挂)1、该软件可以轻松地帮助玩家将...
aapoker有外 挂!德州a... aapoker有外 挂!德州aapoker下载,(aApoker)其实真的有挂,详细教程(有挂技巧)...