加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – View中的意外NullReferenceException

发布时间:2020-12-15 20:36:07 所属栏目:asp.Net 来源:网络整理
导读:我有一个Razor视图,开头像: @using My.Models@model MySpecificModel@{ ViewBag.Title = "My Title"; // NullReferenceException here: string dateUtc = (Model == null ? DateTime.UtcNow.ToShortDateString() : Model.Date.ToShortDateString()); 我在最
我有一个Razor视图,开头像:
@using My.Models
@model MySpecificModel
@{
    ViewBag.Title = "My Title";  
    // NullReferenceException here:
    string dateUtc =  
        (Model == null ? DateTime.UtcNow.ToShortDateString() :
                         Model.Date.ToShortDateString());

我在最后一行看不到NullReferenceException的原因(注意:“=?:”的东西在我的源代码中的一行.它被格式化为适合这里.)

然后我删除dateUtc的/ assignment赋值,NullReferenceException移动到ViewBag.Title行:

@using My.Models
@model MySpecificModel
@{
    ViewBag.Title = "My Title";  // NullReferenceException here:

怎么可能发生这种情况? ViewBag当然不是null.

注1:仅当Model为null时才会发生这种情况.

注2:MySpecificModel.Date的类型为DateTime,因此永远不能为null.

解决方法

您提供了一个空的默认模型,它什么也不做.这将是模型不为空.它将有助于拥有IsEmpty属性.更好的是,如果可以在您的情况下应用,则使用具有默认值的模型.重要的是模型永远不会为空

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读