ASP.NET MVC从资料中显示用户名 [英] ASP.NET MVC displaying user name from a Profile
问题描述
以下是在 LogOn支持从标准的默认ASP.NET MVC项目由Visual Studio创建的用户控件( LogOnUserControl.ascx )
The following is the LogOn user control from a standard default ASP.NET MVC project created by Visual Studio (LogOnUserControl.ascx):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%: Page.User.Identity.Name %></b>!
[ <%: Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<%
}
else {
%>
[ <%: Html.ActionLink("Log On", "LogOn", "Account")%> ]
<%
}
%>
这插入母版页:
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
的&LT;%:Page.User.Identity.Name%&GT;
code显示用户的登录名当前登录
The <%: Page.User.Identity.Name %>
code displays the login name of the user, currently logged in.
如何显示用户的姓
来代替,这是保存在个人资料?
How to display the user's FirstName
instead, which is saved in the Profile?
我们可以像下面的控制器阅读:
We can read it in a controller like following:
ViewData["FirstName"] = AccountProfile.CurrentUser.FirstName;
如果我们,例如,尝试做这样的:
If we, for example, try to do this way:
<%: ViewData["FirstName"] %>
这使得只有那些被称为由其中计算机[名字]
价值分配控制器中的页面上。
It renders only on the page which was called by the controller where the ViewData["FirstName"]
value was assigned.
推荐答案
REM,
这是在哪里有一个基本的控制器将解决'所有'你的问题(当然,某些反正)的案件之一。在你的基地控制器,你必须是这样的:
this is one of those cases where having a base controller would solve 'all' your problems (well, some anyway). in your base controller, you'd have something like:
public abstract partial class BaseController : Controller
{
// other stuff omitted
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewData["FirstName"] = AccountProfile.CurrentUser.FirstName;
base.OnActionExecuted(filterContext);
}
}
和使用它在所有的控制器,如:
and use it in all your controllers like:
public partial class MyController : BaseController
{
// usual stuff
}
或相似。那么你会永远拥有它适用于所有控制器的每一个动作。
or similar. you'd then always have it available to every action across all controllers.
看它是否适合你。
这篇关于ASP.NET MVC从资料中显示用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!