我正在开发一个asp mvc应用程序。我想在局部视图中访问当前登录的用户名。我已经检查了net上可用的大多数答案。我将解释我的方案
我的孩子的行动是
public ActionResult LoggedInUserActions()
{
var userId = User.Identity.GetUserId();
var user = dbcontext.Users.SingleOrDefault(a => a.Id == userId);
return PartialView("_HelloUser", user);
}
在布局中使用
@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 :(得分:0)
必须在所需的模型后键入部分视图。添加声明,例如:
@model MyClass
然后您就可以通过@Model属性访问它。 另一种方法是使用视图包来发送数据。在这种情况下,您需要获取操作结果并将数据添加到其视图包中:
var result = PartialView("_HelloUser", user);
result.ViewData["Key"] = Value; //do change Key and Value
return result;