Search code examples
asp.netasp.net-mvcasp.net-mvc-4asp.net-web-apinullreferenceexception

Object reference not set to an instance of an object in line of Layout in View


I am gonna be crazy about this error!

I have a very simple View, without any model or..., and I receive null error in the line of defining Layout, while in the other pages layout works correctly, any idea please?

part of My View:

@{
ViewBag.Title = "رزرو";
Layout = "~/Views/Shared/_Layout.cshtml";   //Error is here
}

and Controller:

     public ActionResult Reserves()
     {
        ViewBag.reservelist = "";
        try
        {
            ViewBag.UnreadMessages = UnreadMessages(Session["PersonId"].ToString());
            Guid DoctorId = Guid.Parse(Session["PersonId"].ToString());
           
            List<Reserve> reservelist = db.Reserves.Where(r => r.DoctorId == DoctorId && r.Accepted 
         == null).ToList();
            ViewBag.reservelist = reservelist;
           
        }
        catch
        {

        }
        return View();
       
    }

Solution

  • I realized what was the problem!

    there was a Session in one of the menu that its value was null and stupid VS couldn't find the problem,

        <li>
             //The below session was null
    
           <a href="@Url.Action("Chat","Home", new { PId = Session["PId"].ToString() })">
            <i class="fas fa-comments"></i>
              <span>پیام‌ها</span>
             <small class="unread-msg">@ViewBag.UnreadMessages</small>
           </a>
          </li>