Thursday, March 28, 2013

Adding custom fields to a VS2012 MVC4 SimpleMembership system

Adding custom fields to a VS2012 MVC4 SimpleMembership system
Add custom columns/fields to your MVC4 SimpleMembership "UserProfile" table
MVC 4 in Visual Studio 2012 introduces the new SimpleMembership Provider as its default web-based authentication system. While this system is much simpler than the earlier ASPNETDB system that it replaces, there definitely are a few new and neat tricks to be learnt.

One of them is: How do I add custom fields to my MVC 4 registration system?

It can be done in just 4 simple steps:

1. Start up VS 2012, and create a new MVC 4 web project. Set up your SimpleMembership registration system - for some help, please see post on setting up a SimpleMembership Provider in a VS2012 MVC4 project.

2. Next, run the project and navigate to the login page, so that the tables get created. It is not necessary to create a user at this point.

3. Then, in your database, alter the table UserProfile, and add a column: FullName (nvarchar(50)).

4. Next, add/reference the new FullName field in the following programs in your project:
In class UserProfile, in AccountModels.cs (to ensure the class matches the table columns):

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
        // Customization: Field(s) added
        public string FullName { get; set; }
    }

In class RegisterModel, in AccountModels.cs (to enable handling on the registration form):

    public class RegisterModel
    {
        // Existing code
        // ...

        // Customization: Field(s) added
        [Required]
        [Display(Name = "Your full name")]
        [DataType(DataType.Text)]
        public string FullName { get; set; }
    }

In the Register.cshtml view (so it'll appear on the user registration form), add a new li element with the following content:
    @Html.LabelFor(m => m.FullName)
    @Html.TextBoxFor(m => m.FullName)

In the [HttpPost] Register ActionResult, in AccountController.cs, modify the call to the CreateUserAndAccount method (to write the new column to your database):
    // Customization: Field(s) added when creating a new account
    WebSecurity.CreateUserAndAccount(
        model.UserName,
        model.Password,
        new { FullName = model.FullName }
        );

Now run your program and register a new user, supplying a value for the FullName field... success! The new row created in your database table contains the value supplied for the new column!

Note: This post covers how to create a custom column. A near-future post will explain how to access the value of that column from within your VS 2012 MVC 4 projects. Please re-visit my blog occasionally :)

Happy coding!

No comments:

Post a Comment