I have a working MVC 4 edit view that edits a stored database record. This is the relevant section of the Controller:
//
// 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);
}
This is the points section of the Model:
[Required(ErrorMessage = "The Points field is required.")]
public int Points { get; set; }
And this is the relevant section of the edit view:
<div class="editor-field">
@Html.DropDownList("Points")
@Html.ValidationMessageFor(model => model.Points)
</div>
When I try to edit a record the points dropdownlist always populates with “0 – (No Points)” no matter what value is stored in the database. Is there a way to bind this dropdownlist so it will display the stored value in the edit view?
You’ll need to use DropDownListFor to hook up the field to your Property. You should be passing down the options on the Model down to the view. You’ll want to write up a view model and pass both the occurences AND the options. Then use DropDownListFor
Populate those in your controller and pass that down instead of using the ViewBag, then use DropDownListFor:
The *For methods will hook up all the relevant “goo” into your html. It ensures an auto-populated value as well as correct binding on the next post.
Good luck.