使用EF将表的主键映射到AspNetUser表作为外键

时间:2015-01-09 00:04:58

标签: c# asp.net-mvc entity-framework

我正在尝试创建一个应用程序,其中我有一个5度的表格,用户可以从下拉列表中选择一个度数。提交后,所选的学位ID将被假设作为外键保存在AspNetUser表中,但在我的代码中没有发生。相反,每当我注册一个新用户时,degree_id列都会留空或“空白”。我正在使用实体框架来构建我的应用程序。

/* 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,
            }
        };

我在寄存器视图模型

中有这行代码
[Display(Name = "Degree")]
public Degree Degree { get; set; }

IdentityModels.cs在ApplicationUser:identityUser class:

下有这行代码
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>

1 个答案:

答案 0 :(得分:0)

  

没有值没有回发

根据您的评论,未正确配置 DropDownList 。这就是为什么你无法检索发布的值。

看看这个例子 -

控制器

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>
}
相关问题