开发者

ASP.NET MVC displaying user name from a Profile

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&g开发者_开发技巧t;

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.

see if it works for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜