Click here to Skip to main content
14,693,352 members
Articles » Web Development » ASP.NET » Howto
Tip/Trick
Posted 15 May 2015

Tagged as

Stats

74K views
12 bookmarked

Displaying User Full Name instead of User Email in AspNet Identity 2.0

Rate me:
Please Sign up or sign in to vote.
4.54/5 (8 votes)
15 May 2015CPOL
How to replace User.Identity.Name (Email) by Full Name in AspNet Identity 2.0

Introduction

AspNet Identity 2.0 with MVC 5 by default displays the username which is user's email address in  _LoginPartial.cshtml page.  I will go through how to change this to user's FirstName and LastName  i.e. Full Name

Background

AspNet Indentity 2.0 uses user email address as user name and displays it on successfull login to confirm the user by showing the partial view _LoginPartial. As default AspNet Identity 2.0 does not store user information such as first name or last name. To store and use user's First Name and Last Name, we can create new columns to the AspNetUsers table or add new table to store them by linking with the AspNetUsers table. I will follow the first approach where I will create two columns named as FirstName and LastName and use them to display the full user name after successful login. 

Description

To start with I am going to create a new  MVC 5 ASP.NET Web application in  using Visual Studio 2013.

Image 1

From the list of available templates I will choose MVC and click OK to create the project.

Image 2

When the project is created, it looks as below in the Solution Explorer:

Image 3

Before doing any change to the project, I will update the database connection string to point to my LocalDb database and change the database name to AspNetIdentity2.

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AspNetIdentity2;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

As I mentioned I will add two columns FirstName and LastName to the user record while registering the user to the application.  

Currently the default registration form does not have First Name or Last Name fields.

Image 4

To add the new two fields we need to make sure that the model data validates the two new fields and they are correctly inserted to the database while the user does the registtraion.

Adding two new properties

I have added FirstName and LastName  properties to the  IdentityModels in ApplicationUser class as below:

public class ApplicationUser : IdentityUser
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }

       public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
       {
           // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
           var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
           // Add custom user claims here
           return userIdentity;
       }
   }

I have also added the same two properties  to the RegisterViewModel class in  AccountViewModels as below:

public class RegisterViewModel
   {
       [Required]
       [EmailAddress]
       [Display(Name = "Email")]
       public string Email { get; set; }

       [Required]
       [DataType(DataType.Text)]
       [Display(Name = "First Name")]
       public string FirstName { get; set; }

       [Required]
       [DataType(DataType.Text)]
       [Display(Name = "Last Name")]
       public string LastName { get; set; }

       [Required]
       [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
       [DataType(DataType.Password)]
       [Display(Name = "Password")]
       public string Password { get; set; }

       [DataType(DataType.Password)]
       [Display(Name = "Confirm password")]
       [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
       public string ConfirmPassword { get; set; }
   }

After that I have added two new text fields to the Registration view to capture user's FirstName and Last Name

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

Having done these, we can see the two new fields in the Register view as below:

Image 5

Updating controller methods

I will update the POST method in Account controller where the information are saved to the database. Here I have added FirstName and LastName to save with Email and Password.

// POST: /Account/Register
       [HttpPost]
       [AllowAnonymous]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Register(RegisterViewModel model)
       {
           if (ModelState.IsValid)
           {

               var user = new ApplicationUser
               {
                   UserName = model.Email,
                   Email = model.Email,
                   FirstName = model.FirstName,
                   LastName = model.LastName
               };

               var result = await UserManager.CreateAsync(user, model.Password);
               if (result.Succeeded)
               {
                   await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                   // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                   // Send an email with this link
                   // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                   // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                   // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                   return RedirectToAction("Index", "Home");
               }
               AddErrors(result);
           }

           // If we got this far, something failed, redisplay form
           return View(model);
       }

Before we run and register for the application, let us migrate the database with the changes for to columns.

 I have run the command from the Package Manager Console

Enable-Migrations

Image 6

After that I run the command

Add-Migration

Image 7

And finally to update the database I issued

Update-Database

Image 8

If we look at AspNetUsers table we can see two new columns which are not present in the original table as shown on the right side.

 

Image 9Image 10

Let us run and register a user to the application

Image 11

After successful registration the Home page looks as below:

Image 12

Updating code to send users' full name to the view

Now I will make changes for displaying the user's Full Name instead of the email address.

I will create a Controller class that will be the base controller for other controllers for the application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AspNetIdentity2.Models;

namespace AspNetIdentity2.Controllers
{
    public class ApplicationBaseController : Controller
    {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (User != null)
            {
                var context = new ApplicationDbContext();
                var username = User.Identity.Name;

                if (!string.IsNullOrEmpty(username))
                {
                    var user = context.Users.SingleOrDefault(u => u.UserName == username);
                    string fullName = string.Concat(new string[] { user.FirstName, " ", user.LastName });
                    ViewData.Add("FullName", fullName);
                }
            }
            base.OnActionExecuted(filterContext);
        }
        public ApplicationBaseController()
        { }
    }
}

I have changed all controller methods to inherit the ApplicationBaseController instead of Controller.

For instance the HomeController inherits ApplicationBaseController as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetIdentity2.Controllers
{
    public class HomeController : ApplicationBaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Now I have changed the _LoginPartial.cshtml  as below to display the user's Full Name from ViewData as the ApplicationBaseController sends the full name.

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated && ViewData.ContainsKey("FullName"))
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Hello " + (ViewData["FullName"]) + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

Now we can see the full name is displayed.

 

Image 13

 

Points of Interest

AspNet Identity 2.0, MVC 5

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mostafa Asaduzzaman
Software Developer (Senior)
Australia Australia
No Biography provided

Comments and Discussions

 
QuestionHow can i display Username instead of First Name and Last Name? Pin
Pankaj Mahor3-Sep-19 6:28
MemberPankaj Mahor3-Sep-19 6:28 
QuestionNice! I was looking to add an AVATAR instead of a name... Pin
Member 1394936229-Aug-18 8:47
MemberMember 1394936229-Aug-18 8:47 
QuestionReally good guide! Pin
Pelle Källström5-Jan-16 8:29
MemberPelle Källström5-Jan-16 8:29 
Questionnice article but i have a question Pin
akanksha srivastava2-Dec-15 1:57
Memberakanksha srivastava2-Dec-15 1:57 
AnswerRe: nice article but i have a question Pin
Mostafa Asaduzzaman2-Dec-15 9:36
MemberMostafa Asaduzzaman2-Dec-15 9:36 
QuestionAnother way of achieving this Pin
Jon Smith24-May-15 10:49
MemberJon Smith24-May-15 10:49 
AnswerRe: Another way of achieving this Pin
Mostafa Asaduzzaman24-May-15 11:17
MemberMostafa Asaduzzaman24-May-15 11:17 
AnswerRe: Another way of achieving this Pin
Member 1088081221-Jun-16 8:46
MemberMember 1088081221-Jun-16 8:46 
AnswerRe: Another way of achieving this Pin
Greg K6-Feb-18 7:21
MemberGreg K6-Feb-18 7:21 
GeneralRe: Another way of achieving this Pin
Swarnakamal Mishra6-Mar-20 21:13
MemberSwarnakamal Mishra6-Mar-20 21:13 
Questionnice article Pin
Member 1170543620-May-15 4:22
MemberMember 1170543620-May-15 4:22 
AnswerRe: nice article Pin
Mostafa Asaduzzaman20-May-15 10:16
MemberMostafa Asaduzzaman20-May-15 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.