Domanda

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.

È stato utile?

Soluzione

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, ....)

Altri suggerimenti

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" })
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top