質問

How can I save data for a multiple DropDownListFor? I have this code but the selected items aren't reaching the controller.

My code view:

@Html.DropDownListFor(model => model.Ingredients, new SelectList(Model.ListIngredients, "Id", "Description"), "Select the ingredients", new { multiple = "multiple", })

My model:

public ICollection<Ingredient> Ingredients { get; set; }
public ICollection<Ingredient> ListIngredients{ get; set; }

Ingredient.cs:

public string Description { get; set; }
public int Id { get; set; }

I have to change the name and id of my helper for data to be saved?

役に立ちましたか?

解決

You are trying to bind the selected values into a collection of Ingredients. However if you take a look at the posted values, they will look something like this:

...Ingredients=1&Ingredients=2...

That means the model binder will not know how to convert values like 1,2 (which are the ingredient Ids) into instances of the ingredient class.


You need to change the property of your view model where you will get the ingredients selected by the user, so instead of a collection of Ingredients:

public ICollection<Ingredient> Ingredients { get; set; }

you have a collection of Ids (which is the property you are using as the value of the multi-select), for example:

public int[] SelectedIngredients { get; set; }

(I have renamed the property but that is not strictly needed, I have done it just for clarity)

As a suggestion, I would remove the default option value from that multi-select (The "Select the ingredients" option) and use a label or tooltip. Otherwise it may look like any other value from the list and you will have to deal with the scenario where the user selects that option, which is not a valid ingredient.

Even better, I would also use the @Model.ListBoxFor helper as that will let everybody know they are dealing with a multi-select. Otherwise (with the drop down helper) you may not realize it is a multi-select unless you look at the attributes. Something like:

 @Html.ListBoxFor(m=>m.SelectedIngredients, new SelectList(Model.ListIngredients, "Id", "Description"))

Of course, these are just suggestions. You can happily Ignore them if they don't apply to your requirements!

As a final comment, it is possible to convert the posted values into Ingredient objects as you initially had in your view model. That would require you to write your own model binder and configure it for the Ingredient type. However you will only receive the id in the posted values, so you would have to retrieve the other properties (from the database probably) or you will have a collection of Ingredient objects where only the Id is populated. I would not go down this route unless you really need to.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top