I am looking for the best method for creating a drop down list editor template with MVC. There seem to be various methods but I can't find any method that is best, everyone seems to do it differently. I am using MVC3 with Razor as well, so a method that works with this is preferred.
+3
A:
There are many ways and saying which is the best would be subjective and might not work in your scenario which by the way you forgot to describe in your question. Here's how I do it:
Model:
public class MyViewModel
{
public string SelectedItem { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public string Value { get; set; }
public string Text { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch this from a repository
Items = new[]
{
new Item { Value = "1", Text = "item 1" },
new Item { Value = "2", Text = "item 2" },
new Item { Value = "3", Text = "item 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// redisplay the view to fix validation errors
return View(model);
}
// TODO: The model is valid here =>
// perform some action using the model.SelectedItem
// and redirect to a success page informing the user
// that everything went fine
return RedirectToAction("Success");
}
}
View (~/Views/Home/Index.cshtml
):
@model MyApp.Models.MyViewModel
@{ Html.BeginForm(); }
@Html.EditorForModel()
<input type="submit" value="OK" />
@{ Html.EndForm(); }
Editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml
):
@model MyApp.Models.MyViewModel
@Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.Items, "Value", "Text"))
Darin Dimitrov
2010-10-25 12:26:12
Thanks for this, it seems to be exactly what I want.
Craig
2010-10-25 21:01:21