Simplest case, I'm creating a "Create View" for a task list, and I want to allow the user to select a "Category" from a related table via a dropdownlist.
Should I
- Create a custom model that contains a Task and an IEnumerable?
- Instanciate the CategoryController from the "Create Task View" and bind开发者_如何学C the DDL via a method on the CategoryController?
- Another option I didn't think of?
Which approach best fits within the MVC design pattern? Which do you use, and more importantly why?
You can do two things:
a) The quick hack
public ActionResult Create() {
ViewData["myList"] = new SelectList( listOfCategories, "Name","CategoryId");
return View()
}
Create.aspx
...
<%= Html.DropDown("categoryId", ViewData["myList"] as SelectList,"-");
...
b) Create a ViewDataModel.
public class CreateProductViewData
{
public Product product { get; private set; };
public SelectList Categories { get; private set; }
public CreateProductViewData(Product p) {
product = p;
Categories = new SelectList( listOfCategories, "Name","CategoryId");
}
}
public ActionResult Create()
{
Product p = new Product() { name="New Product..." } ;
return View(new CreateProductViewData(p));
}
in Create.aspx
...Inherits="System.Web.Mvc.ViewPage<CreateProductViewData>" %>
..
..
<%= Html.DropDown("CategoryId", Model.Categories, "-");
I mostly use approach B, because it moves alot of code out of the controller, and into the "What is needed to display this page"-code, without cluttering the "HOW do i display the data" code.
So in effect I have
- Code that acts (the controller)
- Code that prepares the view, by loading secondary data (The ViewData object)
- Code that renders the view (the .aspx)
Usually I can reuse the ViewDataModel for both Edit and Create.
1 is the most "correct" way.
2 is downright evil, your back in webforms world and throwing away the clean separation of concerns.
3 is unnecessary because I don't know how much you'd gain instead of 1.
精彩评论