ASP.NET MVC Profile Provider

this article will explain how to use the ASP.NET profile provider using the MVC 3 Framework.  The profile provider will allow us to extend the membership service and add custom fields to a user profile. If you want to check out the source without reading ahead, you can download it HERE

Let’s start by creating a new MVC 3 project.  I’ll call mine ProfileExample, but you can call it whatever you’d like.

Now, add a new class in the Models folder.  Call it Profile.cs

Now that we’ve created the Profile class, we’re going to include a library or two, and derive from the ProfileBase.  We’ll add properties for first and last name as well.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.ComponentModel.DataAnnotations;

namespace ProfileExample.Models
{
public class Profile : ProfileBase
{
[Display(Name = "First Name")]
public virtual string FirstName
{
get
{
return (this.GetPropertyValue("FirstName").ToString());
}
set
{
this.SetPropertyValue("FirstName", value);
}
}

[Display(Name = "Last Name")]
public virtual string LastName
{
get
{
return (this.GetPropertyValue("LastName").ToString());
}
set
{
this.SetPropertyValue("LastName", value);
}
}

public static Profile GetProfile(string username)
{
return Create(username) as Profile;
}
}
}

Now, open your Web.config file and find the profile tag.  Modify it to inherit your new Profile class.

Now, all we have to do is modify our Account Model and Controller to accept first and last names and store them. We’ll also have to add fields to the register view to accept the extra inputs.  Open up AccountModels.cs (from the Models folder) and add properties for First and Last name to the Register Model.

public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { 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; }

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

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

Open up the Register.cshtml file under Views > Account and add fields for first and last name.

now if you run the application, and head to the register page, you should see first and last name fields with validation working as intended.

we’re almost there, but not quite done yet.  We have to do a few things in our controller to store the profile information.  Open AccountController.cs and head to the HttpPost Register action.  This is where we will persist the information to the database upon creation.

[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

//add profile information
var profile = Profile.GetProfile(model.UserName);
profile.FirstName = model.FirstName;
profile.LastName = model.LastName;
profile.Save();

return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}

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

You’re all set! The profile information is now being stored in the aspnet_Profile table of your database. To test this out, let’s add the profile information to the home page and display it to the user. Open up HomeController.cs and modify the Index action to look like this

public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
var profile = Profile.GetProfile(User.Identity.Name);
ViewBag.Message = "HELLO " + profile.FirstName + " " + profile.LastName + "!";
}
else
{
ViewBag.Message = "Log on to see your name.";
}

return View();
}

Now, when I log in, my profile information is displayed!

i hope you found this tutorial helpful.  Here’s another link to the source code if you had any trouble along the way.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s