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

相关内容

热门资讯

wepoke辅助德之星!wep... 1、wepoke辅助德之星!wepoke辅助德之星,wepoke支持安卓,技巧教程(有挂攻略);该软...
wpk透视辅助测试!wpK一般... wpk透视辅助测试!wpK一般真的有挂,wpK一般真的有挂,2025教程(有挂解密)1、全新机制【w...
微扑克ai辅助工具!微扑克系统... 您好,微扑克这款游戏可以开挂的,确实是有挂的,需要了解加微【757446909】很多玩家在这款游戏中...
德州AI智能辅助机器人!wep... 德州AI智能辅助机器人!wepoke智能ai,aapoker有外挂(详细透视教程);1.德州AI智能...
WPK透视辅助(wpK)wpk... WPK透视辅助(wpK)wpk怎输赢机制(辅助挂)其实真的有挂(微扑克教程)1、微扑克机器人多个强度...
wepower辅助器!wepo... 《wepower软件透明挂》是一款多人竞技的wepower辅助透视游戏,你将微扑克对手来到同一个战场...
微扑克辅助机器人!微扑克专用辅... 微扑克辅助机器人!微扑克专用辅助程序可以用的啊,微扑克ai技术,存在挂教程(有挂辅助挂)是一款可以让...
德州之星插件!微扑克职业代打,... 此外,数据分析德州(微扑克系统发牌规律)辅助神器app还具备辅助透视行为开挂功能,通过对客户微扑克系...
wpk有外 挂!wpk ai辅... wpk有外 挂!wpk ai辅助有用(Wpk)的确是有挂的-详细辅助挂教程;1、超多福利:超高返利,...
安装教程!wepoke美元局稳... 安装教程!wepoke美元局稳(wepower有外 挂)德州wepower(本来真的有挂);德州we...