ASP.NET MVC displaying user name from a Profile
Asked Answered
R

1

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.

Radioactivity answered 27/10, 2010 at 18:47 Comment(1)
See related link: #976993Gullett
R
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.

Reprobative answered 27/10, 2010 at 18:51 Comment(4)
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)?Radioactivity
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 :)Reprobative
@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.. ;)Voidable
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.NameReprobative

© 2022 - 2024 — McMap. All rights reserved.