Customize the MVC 5 Application Users’ using ASP.Net Identity 2.0

By October 1, 2014 MVC One Comment
aspnetidentity2img1

In ASP.Net MVC 5.0, users and their roles are managed using ASP.Net Identity 2.0. By default when you create a new account email, password and confirm password are required as it’s shown below.
aspnetidentity2img1
You may come across a requirement to modify the required fields for a particular application user. For example, along with the email and password, you want to save the user’s age, country and city. In this post we will learn to modify the user information. Basically there are the three steps involved in this:
aspnetidentity2img2
Modify the ViewModel
To modify the ViewModel, you should change the RegisterViewModel classin the Models\ ViewModel.cs. I have added three more additional fields —  Age, City and Country in the RegisterViewModel.
aspnetidentity2img3
After adding fields, the updated RegisterViewModel will be as shown below:
ViewModel.cs

This is all you should change in the ViewModel to incorporate additional fields.
Modify the View
Next we should modify the View such that the user can see the additional fields. We need to change Register.cshtml in the View folder. An additional three fields are added in the View as shown below:
aspnetidentity2img4
After adding additional fields, RegsiterView.cshtml will look like this:
RegisterView.cshtml

This is all you should change in the View to incorporate additional fields.
Modify the Controller
The last step is to modify the controller so that additional fields will be saved in the database. Before we modify the Controller, ApplicationUser class should be modified with the additional fields. You will find ApplicationUser class in the Model folder. Add three additional fields ( age, City and Country) as properties in the ApplicationUser class.

ApplicationUser.cs

 

Once ApplicationUser is modified, let us modify the Controller. We are passing additional fields information while creating the object of ApplicationUser.

This is all you should do to add more fields in the application user in ASP.Net Identity 2.0. Let us go ahead and run the application to see the change. Now while registering a new user, the application will ask for the additional fields we added like Age, City and Country.

aspnetidentity2img5

Upon clicking the “Register” button, a new user will be created in the application database as shown below,

aspnetidentity2img6

It is as simple as following the above steps to customize users in an MVC application using ASP.Net Identity 2.0.  Happy coding!

The following two tabs change content below.
Dhananjay Kumar is a software engineer, consultant, trainer, blogger and speaker from India. He has been a Microsoft MVP since 2010. He can be followed on twitter @debug_mode.

Latest posts by Dhananjay Kumar (see all)