如何将dropdownlist选择的值保存到数据库int asp.net MVC 5中

时间:2016-02-23 17:58:55

标签: asp.net-mvc asp.net-mvc-4 entity-framework-6

我目前是Asp.net MVC的新手。在其中一个视图中,我添加了一个下拉列表,并将此下拉列表与我的数据库绑定在一起

Controller CollegeController

[HttpGet]
public ActionResult Create()
{
    IEnumerable<SelectListItem> items = db.College_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Name });
    IEnumerable<SelectListItem> item = db.Stream_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Stream });
    ViewBag.CollName=items;
    ViewBag.StreamName = item;
    return View();
}

[HttpPost]
public ActionResult Create(College college)
{
    try
    {
        if(ModelState.IsValid)
        {
            db.Colleges.Add(college);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CollName = db.Colleges;
        return View(college);
    }
    catch
    {
        return View();
    }
}

这是我的模特

public class College
{
    [Required]
    public int Id { get; set; }
    [Required]
    [Display(Name="College Name")]
    public int CollegeName { get; set; }
    [Required]
    public int Stream { get; set; }
    [Required]
    [Column(TypeName="varchar")]
    public string Name { get; set; }
    ....
    public virtual College_Name College_Name { get; set; }
    public virtual Stream_Name Stream_Name { get; set; }
}

这是我的观点

<div class="form-group">
    @Html.LabelFor(model => model.CollegeName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("CollName", (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CollegeName, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Stream, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("StreamName", (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { @class = "form-control" })
       @Html.ValidationMessageFor(model => model.Stream, "", new { @class = "text-danger" })
    </div>
</div>

现在当我保存数据库中的CollegeNameStream之后检查我的数据库时,下拉列表中的数据为零。

1 个答案:

答案 0 :(得分:1)

您的代码存在多个问题。首先,您的下拉列表绑定到名为CollNameStreamName的属性,这些属性甚至不存在于您的模型中。

接下来,您无法将绑定的属性命名为ViewBag属性。

您的观看代码需要(并且始终使用强类型xxxFor() HtmHelper方法

@Html.DropDownListFor(m => m.CollegeName, (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { @class = "form-control" })
....
@Html.DropDownListFor(m => m.Stream, (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { @class = "form-control" }

在您的POST方法中,college.CollegeNamecollege.Stream的值将包含所选选项的ID。

当你在POST方法中返回视图时,你还需要重新填充ViewBag属性(就像在GET方法中那样)或者抛出异常(并注意你当前使用的{{1}也将抛出异常)

我还强烈建议您开始学习使用视图模型(编辑视图不应使用数据模型 - 请参阅What is ViewModel in MVC?) - 并使用反映您的属性的命名约定,例如ViewBag.CollName = db.Colleges; ,或CollegeNameList,而不是CollegeNames