Question

I have a _Layout page and in this _Layout page, I am calling a Partial View as below.

<div>
    @{Html.RenderAction("_Account", "Home");}
</div>

_Account.cshtml

...

    @if (User.Identity.IsAuthenticated)
            {
                <p class="navbar-text navbar-right"> ****I want to write here "UserName"****</p>           }

As you see, I want to write userName if the user is authenticated. ( this is my question :) )

As you can expect, I have an Login controller..

    [HttpPost]
    public ActionResult Index(UserModel model, string returnUrl)
    {
        // My codes for login ...
        var response = _userService.UserGet(request.UserName,request.Password);

        if(response != null)
         {
            ViewBag.UserName = response.User.Name;
         }
      // My another codes....
    }

So, here is my question. I want to use this "ViewBag.UserName" in _Account partial view. I don t wanna use cookies. Is there any way to to id?

Was it helpful?

Solution

You can do it like this:

Main View:

@Html.RenderAction("AccountPartial", "Home")

Action:

[HttpPost]
public ActionResult AccountPartial(UserModel model, string returnUrl)
{
// My codes for login ...
        var response = _userService.UserGet(request.UserName,request.Password);

        if(response != null)
         {
            ViewBag.UserName = response.User.Name;
         }
      // My another codes....
 return PartialView("~/Views/Home/_Account.cshtml",model);
}

Partial View:

@if (User.Identity.IsAuthenticated)
{
 <p class="navbar-text navbar-right">@ViewBag.UserName</p>           
}

OTHER TIPS

As @Satpal said

 @if (User.Identity.IsAuthenticated)
                {
                    <p class="navbar-text navbar-right">@ViewBag.UserName</p>           
    }

Isn't it simple???

just use @User.Identity.Name to get the username

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top