ASP.NET MVC displaying username from profile

The following is a custom LogOn element from the default 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 the main page:

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

The code <%: Page.User.Identity.Name %> displays the username of the user who is currently logged on.

How to display the FirstName user instead, which is saved in the profile?

We can read it in the controller as follows:

 ViewData["FirstName"] = AccountProfile.CurrentUser.FirstName; 

If we, for example, try to do this:

 <%: ViewData["FirstName"] %> 

It is displayed only on the page that was called by the controller, where the value ViewData["FirstName"] was assigned.

+3
asp.net-mvc user-controls master-pages
source share
1 answer

rem

this is one of those cases where the base controller solves "all" your problems (well, some, anyway). in your base controller you will 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, for example:

 public partial class MyController : BaseController { // usual stuff } 

or similar. You will always have access to each action for all controllers.

see if it works for you.

+11
source share

All Articles