title: How to display user name from session in layout page in MVC?
body: <p>i am making mvc project and in layout page i am displaying user name from session variable. If session variable is null then it will display login link. see below code.</p>
  
  <p><strong>_Layout.cshtml</strong></p>
  
  <pre><code>@if (HttpContext.Current.Session["UserId"].ToString() != null &amp;&amp; HttpContext.Current.Session["UserId"].ToString() != "")
  {
      using (Html.BeginForm("LogOff", "Home", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
      {
          &lt;ul class="nav navbar-nav navbar-right"&gt;
              &lt;li&gt;
                  &lt;p&gt;&lt;b&gt;@Session["UserName"]&lt;/b&gt;&lt;/p&gt;
              &lt;/li&gt;
              &lt;li&gt;&lt;a href="javascript:document.getElementById('logoutForm').submit()"&gt;Log off&lt;/a&gt;&lt;/li&gt;
          &lt;/ul&gt;
      }
  }
  else
  {
      &lt;ul class="nav navbar-nav navbar-right"&gt;
          &lt;li&gt;@Html.ActionLink("Register", "Register", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })&lt;/li&gt;
          &lt;li&gt;@Html.ActionLink("Log in", "Login", "Home", routeValues: null, htmlAttributes: new { id = "loginLink" })&lt;/li&gt;
      &lt;/ul&gt;
  }
  </code></pre>
  
  <p>i set session in login action as below.</p>
  
  <p><strong>Controller Action</strong></p>
  
  <pre><code>    [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Login(LoginViewModel login)
      {
          User user = new User();
          user = db.Users.Where(x =&gt; x.UserName == login.UserName &amp;&amp; x.Password == login.Password).FirstOrDefault();
  
          if(user != null)
          {
              Session["UserName"] = user.UserName;
              Session["UserId"] = user.UserName;
              return RedirectToAction("Index");
          }
          else
          {
              return View(login);
          }
      }
  </code></pre>
  
  <p>but i am getting Object reference not set to an instance of an object. error see attached image.</p>
  
  <p><a href="https://i.stack.imgur.com/lHIN5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lHIN5.png" alt="Error of Object reference"></a></p>