I have customized the ASP.NET Simple Membership API and have taken out the call to web security from the Account Controller to my User class. Here's the controller action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateUserAndAccount(user.UserName, user.Password,
new{FirstName = user.FirstName,
LastName= user.LastName,
DateOfBirth= user.DateOfBirth,
IsMale = user.IsMale,
IsClient = user.IsClient,
Email = user.Email});
WebSecurity.Login(user.UserName, user.Password);
return RedirectToAction("Landing", "User");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
db.Users.Add(user);
db.SaveChanges();
}
ViewBag.NationalityId = new SelectList(db.Nationalities, "NationalityId", "NationalityName", user.NationalityId);
ViewBag.UserId = new SelectList(db.UserCardDetails, "UserCardDetailId", "CreditCardNumber", user.UserId);
return View(user);
}
Here's my user class
public class User
{
public int UserId { get; set; }
public int? NationalityId { get; set; }
[StringLength(100)]
public string UserName { get; set; }
[Display(Name = "First Name")]
[StringLength(100)]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[StringLength(100)]
public string LastName { get; set; }
[EmailAddress]
[StringLength(256)]
[Display(Name = "Email ID")]
public string Email { get; set; }
[Display(Name = "Gender")]
public bool? IsMale { get; set; }
[Display(Name="Are you a designer or a client?")]
public bool? IsClient { get; set; }
[Display(Name = "Nationality")]
[ForeignKey("NationalityId")]
public virtual Nationality Nationality { get; set; }
[Display(Name = "Date Of Birth")]
public DateTime? DateOfBirth { 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; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual UserCardDetail UserCardDetail { get; set; }
public User()
{
this.Roles = new List<Role>();
this.Projects = new List<Project>();
this.IsMale = true;
this.IsClient = true;
}
}
When I try to post a data through the form I get and exception which says Password cannot be null. However I'm filling in the password.
Think I just found a fix, I added an extra Property Password = user.Password and it worked.