我在asp.net MVC默认代码中向RegisterViewModel
类添加了两个新字段。验证有效,但新添加的字段的值不会插入数据库,而是插入其他字段。页面不会返回任何错误。
我猜我需要在AccountController
课内做一些事情,在这附近:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
不确定如何。
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
TempData["Email"] = user.Email;
return RedirectToAction("Confirm", "Account");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:1)
如果您需要向数据库添加新字段,则需要添加以修改模型ApplicationUser
而不是viewModel RegisterViewModel
。
因此,在您的问题中,您需要向RegisterViewModel
模型添加新字段,但实际上您需要更新ApplicationUser
类,因为RegisterViewModel
仅用于UI。例如,要添加新字段PersonId
,您需要修改ApplicationUser
模型并迁移数据库
public class ApplicationUser : IdentityUser
{
public string PersonId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
并使用您需要的任何验证将public string PersonId { get; set; }
添加到您的ViewModel RegisterViewModel
,然后在保存代码中将ViewModel转换为模型
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
PersonId = model.PersonId,
};
result = await UserManager.CreateAsync(user, model.Password);
答案 1 :(得分:0)
您没有在ApplicationUser
实例中分配新属性,假设您在模型类中添加了“PhoneNumber”属性,那么您必须将其值复制到用户,如下所示
var user = new ApplicationUser { UserName = model.Email, Email = model.Email,PhoneNumber=model.PhoneNumber };