Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display user name from session in layout page in MVC?

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.

_Layout.cshtml

@if (HttpContext.Current.Session["UserId"].ToString() != null && HttpContext.Current.Session["UserId"].ToString() != "")
{
    using (Html.BeginForm("LogOff", "Home", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        <ul class="nav navbar-nav navbar-right">
            <li>
                <p><b>@Session["UserName"]</b></p>
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Home", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

i set session in login action as below.

Controller Action

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel login)
    {
        User user = new User();
        user = db.Users.Where(x => x.UserName == login.UserName && x.Password == login.Password).FirstOrDefault();

        if(user != null)
        {
            Session["UserName"] = user.UserName;
            Session["UserId"] = user.UserName;
            return RedirectToAction("Index");
        }
        else
        {
            return View(login);
        }
    }

but i am getting Object reference not set to an instance of an object. error see attached image.

Error of Object reference

like image 738
Karan Patel Avatar asked Oct 29 '25 11:10

Karan Patel


2 Answers

This

@if (HttpContext.Current.Session["UserId"].ToString() != null && 
     HttpContext.Current.Session["UserId"].ToString() != "")

should be replaced with

@if (HttpContext.Current.Session["UserId"] != null &&
...

The problem in your code is that .ToString() can only be called on a non-null reference and your code doesn't prevent this at the moment.

like image 147
Wiktor Zychla Avatar answered Oct 31 '25 00:10

Wiktor Zychla


If C# 6.0 (by default in VS2015) is available, null conditional operator can be used to obtain a more elegant code:

@HttpContext.Current.Session["UserId"]?.ToString() ?? "anonymous"

Also, I think that coalesce (??) can be skipped if empty string is required for non-authenticated users.

@HttpContext.Current.Session["UserId"]?.ToString()
like image 40
Alexei - check Codidact Avatar answered Oct 30 '25 23:10

Alexei - check Codidact