ASP.NET MVC DropDown Editor Template
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, e开发者_C百科veryone seems to do it differently. I am using MVC3 with Razor as well, so a method that works with this is preferred.
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"))
This is my approach from this post:
One EditorTemplate for all DropDownLists in ASP.Net MVC
Personally I think that list items should be placed in the view data not the view model but it really depends if you are displaying a drop down that never changes (using view data) or if you'll have to modify it dynamically (using a view model).
In the example you are posting the same view model to the index action. The index action is only interested in the selected item so could just change the parameter of the index post action to be string selectedItem. That way the model binder will look into the form parameters and populate the index parameter for you.
Also, I think it would be better to pass a list of SelectedListItems down to the view that way you wouldn't need any convertion and wouldn't need the Item class.
精彩评论