Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop throws null exception but object is not

i have mvc 4 master page where i want to display user specific menu at the top of the page i am retrieving user data

@using Agenda_MVC.Engine
@{

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

but when i iterate through the list it throws null exception, on setting breakpoint the list is not null it has items.

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

enter image description here

i dont know what i am doing wrong.


code for method is below i am retrieving it from a web service

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;
}
like image 990
Syed Waqas Avatar asked Apr 24 '13 12:04

Syed Waqas


1 Answers

I assume ContactEvent.Name or EventId is null

You can check if both of these values are null in the debugger or by specifying a conditional before assigning the ContactEvent.Name to the ActionLink value.

<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>   
like image 98
Darren Avatar answered Nov 05 '22 23:11

Darren