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.