2017-08-22 414 views
0

我正在开发一个asp mvc应用程序。我想在局部视图中访问当前登录的用户名。我已经检查了net.I提供最答案将解释我的方案在部分视图中访问模型

我的孩子动作

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

使用

@Html.Action("LoggedInUserActions") 

我hellouser局部视图包含

@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>  
      } 
      } 

我的问题是我如何访问我从操作方法访问的用户详细信息局部视图?这是访问当前登录用户名字的好方法吗?有人能帮我吗?

+0

https://stackoverflow.com/questions/263486/how-to-get-the-current-user -in-asp-net-mvc –

+0

我不想获取user.identity.name。我想要First name属性。现在我在该操作方法中添加了一个viewbag,以将用户名称带到部分视图。那很好吗? – Abhijith

+0

您是否在PartialView中声明了您的模型? –

回答

0

必须在您想要的模型之后键入您的部分视图。添加一个声明,如:

@model MyClass 

然后您将能够通过@Model属性访问它。 另一种选择是使用视图包发送数据。在这种情况下,你需要获得行动结果的保持和数据添加到其观点袋:

var result = PartialView("_HelloUser", user); 
result.ViewData["Key"] = Value; //do change Key and Value 
return result; 
+1

嗯,我终于解决了它!我使用了带有控制器和区域名称的@ Html.Action(“LoggedInUserActions”)。 @ Html.Action(“LoggedInUserActions”,“Home”,new {area =“”})。 – Abhijith