-2

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
doganilker
  • 103
  • 2
  • 16

3 Answers3

0

As @Satpal said

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

Isn't it simple???

Richa
  • 3,261
  • 2
  • 27
  • 51
  • hi Satpal. No it is not working. I am creating this ViewBag in Login controller which has no relation with _layout page or _Account partial view. I must do something to pass this parameter to this partial view.. – doganilker Apr 09 '14 at 07:39
  • See following link and you will understand everything http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/various-ways-to-pass-data-from-controller-to-view-in-mvc/ – Richa Apr 09 '14 at 07:42
0

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>           
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

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

Matt Tabor
  • 1,053
  • 8
  • 10