0

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 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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.