3

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

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 - 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 :)
@jimtollan- I like your answer. I just want to know what is that AccountProfile represents? Because I'm also wants to implement it on my system but get a red mark on it.. thanks.. ;)
hi bot. AccountProfile.CurrentUser.FirstName is a custom profile object that ihad in my code at that point in time. for your purposes, i gues you might use User.Identity.Name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.