ASP.NET MVC displaying user name from a Profile

妖精的绣舞 提交于 2019-12-12 08:57:14

问题


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")%> ]
<%
}
%>

which is inserted into a master page:

<div id="logindisplay">
    <% Html.RenderPartial("LogOnUserControl"); %>
</div>

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.


回答1:


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.

see if it works for you.



来源:https://stackoverflow.com/questions/4036582/asp-net-mvc-displaying-user-name-from-a-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!