c# - 如何将我的注册表单中的信息发布到 MVC 5 中的 AspNetUser 表
问题描述
我正在开发一个应用程序,学生可以在该应用程序中选择他们的部门和角色,同时注册到该站点。我能够在注册表单中添加选择部门和角色的选项。实际上,部门的 DropDownList 是从数据库中的部门表中填充的。但是当我在填写表格后尝试注册用户时,我收到此错误消息
“/”应用程序中的服务器错误。INSERT 语句与 FOREIGN KEY 约束“FK_dbo.AspNetUsers_dbo.Departments_DepartmentID”冲突。冲突发生在数据库“aspnet-AptechAPP-20180514123201”、表“dbo.Departments”、列“DepartmentID”中。该语句已终止。
下面是我的 RegisterViewModel 的屏幕截图
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { 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 int DepartmentID { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> DepartmentList
{
get; set;
}
}
我的注册视图控制器
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))
.ToList(), "Name", "Name");
RegisterViewModel model = new RegisterViewModel();
ConfigureRegisterViewModel(model);
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureRegisterViewModel(model);
return View(model);
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, DepartmentID = model.DepartmentID };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// 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>");
return RedirectToAction("Index", "Home");
}
ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))
.ToList(), "Name", "Name");
AddErrors(result);
// If we got this far, something failed, redisplay form
ConfigureRegisterViewModel(model);
return View(model);
}
private void ConfigureRegisterViewModel(RegisterViewModel model)
{
IEnumerable<Department> departments = db.Departments.OrderBy(u => u.DepartmentName).ToList();
model.DepartmentList = departments.Select(a => new SelectListItem
{
Value = a.DepartmentID.ToString(),
Text = a.DepartmentName.ToString()
});
}
我的部门视图模型
public class Department
{
public virtual int DepartmentID { get; set; }
public virtual string DepartmentName { get; set; }
}
我的身份模型
public class ApplicationUser : IdentityUser
{
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 int DepartmentID { get; set; }
public virtual Department Department
{
get; set;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
注册.cshtml
<div class="form-group">
@Html.LabelFor(model => model.DepartmentID, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.DepartmentID, Model.DepartmentList, "Please select", new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.Label("user Role", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@*@Html.DropDownList("Name")*@
@Html.DropDownList("UserRoles", (SelectList)ViewBag.Name, " ")
</div>
</div>
解决方案
您正在向其中插入数据的目标表与另一个表中的部门 ID 具有外键关系。在插入数据之前,Department ID 必须首先存在于另一个表中。是否选择了有效的部门 ID?选择时的部门 ID 是什么?该部门 ID 是否存在于另一个表中?
var user = new ApplicationUser
{ UserName = model.Email,
Email = model.Email,
DepartmentID = model.DepartmentID //here?
};
推荐阅读
- arrays - 接受对象数组的 vue 自动完成输入
- spring-boot - Hystrix假装重试超时不起作用
- r - 如何显示每种科目在不同时期的速度进展
- php - PHP - 如何在 foreach 循环中按字母顺序排序名称而不是 ID?
- javascript - 如何检查我推入对象的对象数组是否具有来自另一个对象数组的特定键值
- azure - 生成的工件文件夹层数过多
- python - tesseract 用阿拉伯语返回颠倒的单词
- java - 如何在 Hibernate 上使用 Redis 作为 L2 缓存?
- c# - 在 ASP.NET Core 3.1 中使用 SmtpClient 发送电子邮件附件给出“无法访问关闭的流”。
- mysql - mysql查询中的括号给出不同的结果