C# 使用EF将表的主键作为外键映射到AspNetUser表
我正在尝试创建一个应用程序,其中有一个5度的表,用户可以从下拉列表中选择一个度。提交后,所选学位的id将作为外键保存在AspNetUser表中,但我的代码中不会出现这种情况。相反,每当我注册一个新用户时,degree_id列就会被保留为空或“NULL”。我正在使用实体框架构建我的应用程序C# 使用EF将表的主键作为外键映射到AspNetUser表,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我正在尝试创建一个应用程序,其中有一个5度的表,用户可以从下拉列表中选择一个度。提交后,所选学位的id将作为外键保存在AspNetUser表中,但我的代码中不会出现这种情况。相反,每当我注册一个新用户时,degree_id列就会被保留为空或“NULL”。我正在使用实体框架构建我的应用程序 /* This is my Account/Register Controller */ [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] pub
/* This is my Account/Register Controller */
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
StudentId = model.StudentId,
Degree = model.Degree,
UserProfileInfo = new UserProfileInfo
{
CurrentCourses = model.CurrentCourse,
TakenCourses = model.TakenCourse,
PlannedCourses = model.PlannedCourse,
appointment = model.Appointment,
}
};
IdentityModels.cs在ApplicationUser:identityUser类下有以下代码行:
public class ApplicationUser : IdentityUser
{
.
.
.
public virtual Degree Degree { get; set; }
.
.
.
.
.
}
我的注册视图如下所示:
<div class="form-group">
@Html.LabelFor(model => model.Degree, "Degree", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Degrees", new SelectList(ViewBag.Degrees, "Id", "Title"), "-- Select Degree --", htmlAttributes: new { @class = "form-control" })
</div>
否该值不回发 根据您的评论,DropDownList配置不正确。这就是您无法检索已发布值的原因 看看这个例子- 控制器 模型 看法
是否可以确保表单发回时model.Degree已选择值?否该值未发回
<div class="form-group">
@Html.LabelFor(model => model.Degree, "Degree", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Degrees", new SelectList(ViewBag.Degrees, "Id", "Title"), "-- Select Degree --", htmlAttributes: new { @class = "form-control" })
</div>
public class YourController : Controller
{
public ActionResult Index()
{
var model = new RegisterViewModel();
model.Degrees = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
new SelectListItem { Text = "Two", Value = "2"},
new SelectListItem { Text = "Three", Value = "3"},
};
return View(model);
}
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
string degreeId = model.SelectedDegreeId;
}
}
public class RegisterViewModel
{
public string SelectedDegreeId { get; set; }
public IEnumerable<SelectListItem> Degrees { get; set; }
}
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.SelectedDegreeId, Model.Degrees)
<button type="submit">Submit</button>
}