将listboxfor发送到控制器

时间:2015-03-23 15:45:29

标签: c# forms asp.net-mvc-4

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

当用户按下“提交”字样时按钮我希望列表框中的所有值都放在我的模型属性List中。

以下是我视图中的列表框:

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

此行给出一个错误,即List必须包含SelectListItem。即使我改变了这一点,并在我的视图模型中进行了更改,它仍然无法正常工作。

这是我的viewmodel:

 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));
    }

我想要的是在控制器中,我希望模型List Ingredients由视图中列表框中的所有项目/值填充,但我无法弄明白。

1 个答案:

答案 0 :(得分:3)

多重选择回发一组简单值(比如[1, 4, 7]["Recipe 2", "Recipe 4" ],具体取决于所选选项的值)。您无法将ListBoxFor绑定到复杂对象的集合。您的视图模型需要具有要绑定的属性。假设type 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)
  ....
}
相关问题