如何在编辑视图中创建DropDownList显示已存储的数据库值?

时间:2012-11-28 22:05:50

标签: asp.net razor asp.net-mvc-4

我有一个有效的MVC 4编辑视图,用于编辑存储的数据库记录。这是财务主任的相关部分:

    //
    // GET: /Occurrence/Edit/5

public ActionResult Edit(int id = 0)
    {
        Occurrence occurrence = db.Occurrences.Find(id);
        if (occurrence == null)
        {
            return HttpNotFound();
        }

        List<SelectListItem> points = new List<SelectListItem>()
        { 
            new SelectListItem() { Text = "0 - (No Points)", Value = "0"},
            new SelectListItem() { Text = "1 - (5 to 14 minutes)", Value = "1"},
            new SelectListItem() { Text = "2 - (15 minutes to 1 hour)", Value = "2"},
            new SelectListItem() { Text = "3 - (1 to 3 hours)", Value = "3"},
            new SelectListItem() { Text = "5 - (Over 3 hours)", Value = "5"},
        };

        ViewBag.Points = points;

        ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "EmployeeName", occurrence.EmployeeID);
        return View(occurrence);
}

这是模型的分数部分:

[Required(ErrorMessage = "The Points field is required.")]
public int Points { get; set; }

这是编辑视图的相关部分:

    <div class="editor-field">
        @Html.DropDownList("Points")
        @Html.ValidationMessageFor(model => model.Points)
    </div>

当我尝试编辑记录时,无论数据库中存储了什么值,点下拉列表总是填充“0 - (无点)”。有没有办法绑定此下拉列表,以便在编辑视图中显示存储的值?

1 个答案:

答案 0 :(得分:0)

您需要使用DropDownListFor将字段连接到您的Property。您应该将模型上的选项向下传递给视图。您将要编写视图模型并传递出现和选项。然后使用DropDownListFor

public class ViewModel {

    public List<SelectListItem> PointOptions { get; set; }

    [Required(ErrorMessage = "The Points field is required.")]
    public int Points { get; set; }
}

填充控制器中的那些并传递它而不是使用ViewBag,然后使用DropDownListFor:

@Html.DropDownListFor(m => m.Points, Model.PointOptions)

* For方法会将所有相关的“goo”连接到你的html中。它确保自动填充值以及在下一篇文章中正确绑定。

祝你好运。

相关问题