发送 listboxfor 到控制器

Send listboxfor to controller

我的视图中有一个包含列表框的表单。用户向列表框添加值。

当用户按下 'submit' 按钮时,我希望列表框中的所有值都放在我的模型 属性 中,这是一个列表。

这是我认为的列表框:

 @Html.ListBoxFor(m => m.Ingredients, new List<Ingredient>(), new { @class = "form-control" , @id = "Ingredients"})

这一行报错,List必须包含SelectListItem。即使我更改为那个,并在我的视图模型中更改它,它仍然不起作用。

这是我的视图模型:

 public class RecipeModel
{
    public int Id { get; set; }

    public string Name { get; set; }

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

    public string Description { get; set; }

    public string ImageUrl { get; set; }

    public List<RecipeModel> Recipes { get; set; }
}

这是我的控制器:

[HttpPost]
    public void SaveRecipe(RecipeModel model)
    {
        RecipeDb.SaveRecipe(Mapper.Map<Recipe>(model));
    }

我想要的是在控制器中,我希望模型列表成分由视图中列表框中的所有 items/values 填充,但我无法弄清楚。

A multiple select post back array of simple values (say [1, 4, 7] or ["Recipe 2", "Recipe 4" ] depending on the values of the selected options) .您不能将 ListBoxFor 绑定到复杂对象的集合。您的视图模型需要绑定到 属性。假设 typeof Ingredient 包含属性 int IDstring Name,那么您的视图模型将类似于

public class RecipeViewModel
{
  public int[] SelectedIngredients { get; set; }
  public SelectList IngredientList { get; set; }
}

然后控制器

public ActionResult Create()
{
  RecipeViewModel model = new RecipeViewModel();
  // Populate the collection of available ingredients
  model.IngredientList = new SelectList(db.Ingredients, "ID", "Name");
  // if you want to pre select some options, then: model.SelectedIngredients = new int[] { 1, 4, 7 };
  return View(model);
}

[HttpPost]
public ActionResult Create(RecipeViewModel model)
{
  // model.SelectedIngredients will contain the ID's of the selected ingredients
}

并且在视图中

@model RecipeViewModel
@using(Html.BeginForm())
{
  ....
  @Html.ListBoxFor(m => m.SelectedIngredients, Model.IngredientList)
  ....
}