0

I am developing an asp mvc application. I want to access currently logged in user name in partial view. I have checked most answers available on net.I will explain my scenario

My child action is

  public ActionResult LoggedInUserActions()
    {
        var userId = User.Identity.GetUserId();
        var user = dbcontext.Users.SingleOrDefault(a => a.Id == userId);
        return PartialView("_HelloUser", user);
    }

in layout iam using

@Html.Action("LoggedInUserActions")

My hellouser partial view contains

 @using Microsoft.AspNet.Identity   
    @if (Request.IsAuthenticated) { 

    using (Html.BeginForm("LogOff", "Account",new{area=""}, FormMethod.Post, new { @class = "navbar-right" }))
    {
                @Html.AntiForgeryToken()
                <div class="btn-group show-on-hover" style="z-index:9999">
                    <p style="float:left">Hello! @Model.?
                      </p>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" style="margin-left:8px">
                        Action <span class=" caret">
                        </span>
                    </button>
                    <ul class="dropdown-menu" role="menu" style="z-index:9999">
                        @*<li><a href="#">My Orders</a></li>*@
                        <li>@Html.ActionLink("My Account", "Index","Home", new { Area="User"},null)</li>

                        @*<li class="divider"></li>*@
                        <li><button type="submit" class=" " style="width: 100%;background-color: darkorange">Log Off</button></li>    
                    </ul>
                </div>    
            }   
            }

My question is how can i access the user details i accessed from action method to this partial view? is this a good method to access currently logged in users first name? Can someone help me?

Abhijith
  • 73
  • 2
  • 12

1 Answers1

0

Your partial view must be typed after the model you want. Add a declaration such as:

@model MyClass

and then you will be able to access it through the @Model property. Another alternative is to use the view bag for sending data. In this case, you need to get hold of the action result and add data to its view bag:

var result = PartialView("_HelloUser", user);
result.ViewData["Key"] = Value;  //do change Key and Value
return result;
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • 1
    Well i finally solved it! I used @Html.Action("LoggedInUserActions") with controller and area name. @Html.Action("LoggedInUserActions", "Home", new { area=""}). – Abhijith Aug 22 '17 at 15:19