WebMatrix.WebSecurity默认只会创建一个userid和username的UserProfile表,而我们可能需要很多别的user属性,怎么办呢?
比如要增加一个Sex属性
1。在数据库UserProfile表中增加Sex属性,bit类型
2。在RegisterModel中增加Sex属性
public class RegisterModel { [Required] [Display(Name = "用户名")] public string UserName { get; set; } [Required] [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "密码")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "确认密码")] [Compare("Password", ErrorMessage = "密码和确认密码不匹配。")] public string ConfirmPassword { get; set; } [Display(Name="性别")] public bool Sex{ get; set; } }
3。修改Register方法,这里最好是传入一个匿名类,因为CreateUserAndAccount方法接受的是一个values参数,而他会解析values的所有属性和值再转换成UserProfiles的列:
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // 尝试注册用户 try { WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Sex = model.Sex});
4。在Register View中增加Sex字段:
@model Mvc4Application.Models.RegisterModel @{ ViewBag.Title = "注册"; } <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>创建新帐户。</h2> </hgroup> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary() <fieldset> <legend>注册表单</legend> <ol> <li> @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName) </li> <li> @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password) </li> <li> @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword) </li> <li> @Html.LabelFor(m => m.Sex) @Html.CheckBoxFor(m => m.Sex) </li> </ol> <input type="submit" value="注册" /> </fieldset> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }