通常_LoginPartial.cshtml有下一个:
Hello, @Html.ActionLink(User.Identity.Name, "Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!
我想使用LoginModel模型中的自定义字段而不是User.Identity.Name。 我怎么能这样做?
或者可以设置为User.Identity.Name而不是登录吗?
答案 0 :(得分:7)
对于全局内容,例如您的布局,如果您尚未使用,则应该使用子操作。尝试为每个视图单独填充ViewBag
变量只会导致失败,因为您不可避免地会忘记,或者某些新开发者不知道这样做。
通过子操作,您可以将您喜欢的任何模型作为模型传递到部分视图,这使您能够从持久存储中实际查找用户并使用您喜欢的任何属性。
[ChildActionOnly]
public ActionResult LoginPartial()
{
// ASP.NET Identity
var user = UserManager.FindById(User.Identity.GetUserId());
// Membership
// var user = db.UserProfiles.SingleOrDefault(m => m.UserName == User.Identity.Name);
return PartialView("_LoginPartial", user);
}
然后在您的部分视图中,为身份:
@model Namespace.To.ApplicationUser
或者,使用会员资格
@model Namespace.To.UserProfile
然后,继续引用您喜欢的用户实例中的任何属性。
在布局中调用子操作:
@Html.Action("LoginPartial", "Account")
(我以为您已将孩子的行为放在AccountController
中,这似乎是最合乎逻辑的地方)
答案 1 :(得分:2)
您可以使用ViewBag将信息从Controller操作传递到视图。因此,您可以在OnActionExecuting中设置ViewBag的基本控制器中创建一个继承自Controller的基本控制器。所有其他控制器都可以从Base Controller继承。
然后您可以在布局或任何其他部分视图中使用Viewbag。