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

相关内容

热门资讯

关于透视!xpoker透视辅助... 关于透视!xpoker透视辅助!都是真的有辅助工具(有挂功能)-哔哩哔哩1、完成xpoker透视辅助...
解谜透视!哈糖大菠萝怎么挂!切... 解谜透视!哈糖大菠萝怎么挂!切实存在有辅助神器(有挂神器)-哔哩哔哩1、进入游戏-大厅左侧-新手福利...
揭露透视!聚星ai辅助工具下载... 揭露透视!聚星ai辅助工具下载!原来真的有辅助教程(详细教程)-哔哩哔哩1、在聚星ai辅助工具下载插...
解迷透视!cloudpoker... 解迷透视!cloudpoker外开挂!其实存在有辅助神器(果真有挂)-哔哩哔哩1、这是跨平台的clo...
揭幕透视!werplan外卦神... 揭幕透视!werplan外卦神器!其实是真的有辅助app(有人有挂)-哔哩哔哩1、werplan外卦...
有挂透视!佛手在线大菠萝智能辅... 有挂透视!佛手在线大菠萝智能辅助器!好像是有辅助工具(有挂方法)-哔哩哔哩1)佛手在线大菠萝智能辅助...
开挂透视!约局吧德州真的有透视... 开挂透视!约局吧德州真的有透视挂吗!本来有辅助攻略(有挂存在)-哔哩哔哩亲,关键说明,约局吧德州真的...
总结透视!pokermaste... 总结透视!pokermaster辅助器!好像是真的有辅助神器(竟然有挂)-哔哩哔哩1、pokerma...
详情透视!红龙poker辅助工... 详情透视!红龙poker辅助工具!一直一直总是有辅助工具(讲解有挂)-哔哩哔哩1、让任何用户在无需红...
曝光透视!哈糖大菠萝有挂吗5个... 曝光透视!哈糖大菠萝有挂吗5个常用方法!竟然真的是有辅助插件(有挂细节)-哔哩哔哩在进入哈糖大菠萝有...