【问题标题】:foreach loop throws null exception but object is notforeach 循环抛出空异常,但对象不是
【发布时间】:2013-04-24 12:55:25
【问题描述】:

我有 mvc 4 母版页,我想在其中显示用户特定的菜单 在页面顶部,我正在检索用户数据

@using Agenda_MVC.Engine
@{

    List<Format> ContactEvents = Agenda_MVC.Classes.Utility.GetContactEventFormats(User.Identity.Name);
}

但是当我遍历列表时它会抛出空异常,在设置断点时列表不为空它有项目。

@foreach (var ContactEvent in ContactEvents)
                {
                    <div class="@(ContactEvent.EventId == ViewContext.RouteData.Values["id"].ToString() ? "StaticMenuItemSelected" : "StaticMenuItem")">
                       @Html.ActionLink(ContactEvent.Name.Length > 15 ? ContactEvent.Name.Substring(0, 15) + "..." : ContactEvent.Name, "Agenda", "Portal", new { id = ContactEvent.EventId }, new { @title = ContactEvent.Name })
                    </div>    
                }

我不知道我做错了什么。


方法代码如下,我正在从网络服务中检索它

public static List<Format> GetContactEventFormats(string ContactId)
{
    //List<Format> EventFormats = HttpContext.Current.Cache["EventFormats" + ContactId] as List<Format>;
    List<Format> EventFormats = HttpContext.Current.Session["EventFormats" + ContactId] as List<Format>;

    if (EventFormats == null)
    {
        EngineClient EngClient = Params.GetEngineClient();
        EventFormats = EngClient.GetContactEventFormats(ContactId);

        if (EventFormats != null && EventFormats.Count > 0)
        {
            //HttpContext.Current.Cache.Insert("EventFormats" + ContactId, EventFormats, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
            HttpContext.Current.Session["EventFormats" + ContactId] = EventFormats;
        }
    }

    return EventFormats == null ? new List<Format>() : EventFormats;
}

【问题讨论】:

  • 发布 ContactEvents 的代码。也许它以某种方式延迟初始化并在第一次调用时返回 null,而在第二次调用时返回非 null
  • 也许 'ContactEvent' 之一是 'null' 并且因为调用 '.Name' 和 '.EventId' 而出现异常?
  • @mgttlinger 没有一个 ContactEvent 为空,因为昨天相同的代码还在工作
  • @alex 我已经在下面发布了代码

标签: c# .net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

我假设 ContactEvent.NameEventId 为空

您可以在 debugger 中检查这两个值是否为空,或者在将 ContactEvent.Name 分配给 ActionLink 值之前指定一个条件。

<div class="@(ContactEvent.EventId == ViewContext.RouteData.Values["id"].ToString() ? "StaticMenuItemSelected" : "StaticMenuItem")">

                @if (ContactEvent.Name != null) {
                   @Html.ActionLink(ContactEvent.Name.Length > 15 ? ContactEvent.Name.Substring(0, 15) + "..." : ContactEvent.Name, "Agenda", "Portal", new { id = ContactEvent.EventId }, new { @title = ContactEvent.Name })
                }
                </div>   

【讨论】:

  • @user1799320 - 还要确保 ViewContext.RouteData.Values["id"] 有一个值。
  • 在到达该行之前,任何对象的成员都不是 null 作为它的抛出异常,它在左大括号处抛出。我可以看到对象中的所有值和对象本身
  • @user1799320 - ViewContext.RouteData.Values["id"] 有值吗?
  • ViewContext.RouteData.Values["id"] 为空,谢谢我将其更改为
  • @user1799320 - 没问题。记得把它标记为答案。
【解决方案2】:

在调试期间查看 List 中的 ContactEvent 对象。

也许(可能)一个或多个字段,例如:ContactEvent.EventIdContactEvent.Name 为空。

【讨论】:

  • 不,他们不是我可以确认当我向下钻取对象时
猜你喜欢
相关资源
最近更新 更多
热门标签