-1

I have read many times experts of MVC saying that if I were to use a SelectList, it's best to have a IEnumerable<SelectList> defined in my model.
For example, in this question.
Consider this simple example:

public class Car()
{
    public string MyBrand { get; set; }
    public IEnumerable<SelectListItem> CarBrands { get; set; } // Sorry, mistyped, it shoudl be SelectListItem rather than CarBrand
}

In Controller, people would do:

public ActionResult Index() 
{
    var c = new Car
    {
        CarBrands = new List<CarBrand>
        {
            // And here goes all the options..
        }
    }
    return View(c);
}

However, from Pro ASP.NET MVC, I learned this way of Creating a new instance.

public ActionResult Create() // Get
{
    return View()
}
[HttpPost]
public ActionResult Create(Car c)
{
    if(ModelState.IsValid) // Then add it to database
}

My question is: How should I pass the SelectList to View? Since in the Get method there is no model existing, there seems to be no way that I could do this.
I could certainly do it using ViewBag, but I was told to avoid using ViewBag as it causes problems. I'm wondering what are my options.

Community
  • 1
  • 1
octref
  • 6,521
  • 7
  • 28
  • 44
  • if you want to pass data from controller to view means you should use either model or ViewBag also ViewData can use. Without that you can make static view. – Chandu Jul 17 '13 at 15:43

2 Answers2

1

You could create a ViewModel that has all the properties of Car which you want on your form then make your SelectList a property of that ViewModel class

public class AddCarViewModel
{
   public int CarName { get; set; }
   public string CarModel { get; set; }
   ... etc

   public SelectList MyList
   {
      get;
      set;
   }
}

Your controller will look like

public ActionResult Create() // Get
{
    AddCarViewModel model = new AddCarViewModel();
    return View(model)
}

[HttpPost]
public ActionResult Create(AddCarViewModel c)
{
    if(ModelState.IsValid) // Then add it to database
}

MarkUp

@Html.DropDownListFor(@model => model.ListProperty, Model.MyList, ....)
codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • Sorry, I tried exactly this before but it doesn't work. The problem is that the Controller first direct to the Create of HttpGet, where I would not be able to use any Concrete attributes of model since it just use `return View()`. – octref Jul 17 '13 at 15:43
  • And, by the way, it should be IEnumerable, right? – octref Jul 17 '13 at 15:47
  • @octref I have removed `IEnumerable<...>`. Your create view should instantiate the viewmodel with default properties – codingbiz Jul 17 '13 at 16:48
1

Easy way, this is a copy of my code without model

In the controller

ViewBag.poste_id = new SelectList(db.Postes, "Id", "designation");

In the view

@Html.DropDownList("poste_id", null," -- ", htmlAttributes: new { @class = "form-control" })
barbsan
  • 3,418
  • 11
  • 21
  • 28