add fields

Feb 25, 2012 at 12:50 AM

How can i add another field to the users table ? i want to show some other fields to the register form how can i accomplish this?

Coordinator
Feb 25, 2012 at 9:10 AM

1. User.cs / User.vb - notice the FirstName and LastName properties, in the same way add your own properties

2. WebSecurity.cs / WebSecurity.vb - inspect the Register function, notice FirstName and LastName, add your own properties to the function

Basically Membership.CreateUser is a closed function so you first create the user with this function and upon success fetch the user using regular entity framework methods and update it with your additional properties.

3. Models/AccountModels.cs or Models/AccountModels.vb - add FirstName, LastName and your own properties to the RegisterModel class

4. AccountController, Register HttpPost Action:

 <HttpPost()>
    Public Function Register(model As RegisterModel) As ActionResult
        If ModelState.IsValid Then
            Dim createStatus = WebSecurity.Register(model.UserName, model.Password, model.Email, True, model.FirstName, model.LastName)
            If createStatus = MembershipCreateStatus.Success Then
                Return RedirectToAction("Index", "Home")
            Else
                ModelState.AddModelError("", ErrorCodeToString(createStatus))
            End If
        End If
        Return View(model)
    End Function

[HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus = CodeFirstMembershipSharp.WebSecurity.Register(model.UserName, model.Password, model.Email, true, model.FirstName, model.LastName);
             
                if (createStatus == MembershipCreateStatus.Success)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            return View(model);
        }

5. RightClick the Register Action and scaffold the view based on RegisterModel

Coordinator
Feb 25, 2012 at 9:16 AM

May i ask why did you post this question to the reviews section?

Feb 26, 2012 at 6:43 PM

My bad, i deleted the question in the review sorry.

Thanks for you quick reply, i try what you said but i get an error in the controller method register in this line

 MembershipCreateStatus createStatus = CodeFirstMembershipSharp.WebSecurity.Register(model.UserName, model.Password, model.Email, true, model.FirstName, model.LastName);

the model.FirstName and model.LastName it says "Models.RegisterModel does not have a definition for model.FirstName and model.LastName"

what it could be?

Coordinator
Feb 27, 2012 at 10:40 AM

Add FirstName, LastName properties to your RegisterModel it is located in your models folder