views:

39

answers:

1

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.

+2  A: 

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.

jim
Thanks, jim! Very useful. +1. But how, in this case, I could make sure that ViewData is assigned "AccountProfile.CurrentUser.FirstName" value at the moment of user logged in (right after this moment)?
rem
rem - as long as this AccountProfile is available via some 'mechanism', it'll be available in the override that i txtd above. i know this for a fact as i do this in exactly the same way for a custom profile on an app that i'm working on right now today!! in fact, just try it :)
jim
OK, jim, thank you, I will explore and try it
rem
you won't be sorry - well, not too much anyway!! good luck
jim
@jim, yes, it works, thank you!
rem