开发者

Question regarding generation of ASP.NET MVC "Create" Views

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

  1. Create a custom model that contains a Task and an IEnumerable?
  2. Instanciate the CategoryController from the "Create Task View" and bind开发者_如何学C the DDL via a method on the CategoryController?
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜