[英]Mapping of primary key of a table into AspNetUser Table as foreign key using EF
I'm trying to create an application where I have a table of 5 degrees and a user can select a degree from the drop down list. 我正在尝试创建一个具有5度表的应用程序,用户可以从下拉列表中选择一个度。 Once submitted, the selected degree's id is suppose to be saved in the AspNetUser table as foreign key but that is not happening in my code.
提交后,所选学位的ID应该作为外键保存在AspNetUser表中,但这在我的代码中没有发生。 Instead whenever I'm registering a new user, the degree_id column is being left empty or 'NULL'.
取而代之的是,每当我注册新用户时,degree_id列都将保留为空或为'NULL'。 I'm using entity framework to build my application.
我正在使用实体框架来构建我的应用程序。
/* 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,
}
};
I have this line of code for Degrees in my register view model 我的寄存器视图模型中具有学位的这一行代码
[Display(Name = "Degree")]
public Degree Degree { get; set; }
IdentityModels.cs has this line of code under ApplicationUser : identityUser class: IdentityModels.cs在ApplicationUser下有以下代码行:identityUser类:
public class ApplicationUser : IdentityUser
{
.
.
.
public virtual Degree Degree { get; set; }
.
.
.
.
.
}
And my register view looks like this: 我的注册视图如下所示:
<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>
No the value is not posting back
没有值不回传
Based on your comment, DropDownList is not configured properly. 根据您的评论, DropDownList配置不正确。 It is why you cannot retrieve the posted value.
这就是为什么您无法检索过帐的值。
Look at this example - 看这个例子-
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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.