Send listboxfor to controller

后端 未结 1 1450
[愿得一人]
[愿得一人] 2021-01-23 23:57

I have a form in my view that contains a listbox. The user adds values to the listbox.

When the user pushes the \'submit\' button I want all the values in the listbox to

相关标签:
1条回答
  • 2021-01-24 00:51

    A multiple select post back an array of simple values (say [1, 4, 7] or ["Recipe 2", "Recipe 4" ] depending on the values of the selected options). You cannot bind ListBoxFor to a collection of complex objects. Your view model needs to have a property to bind to. Assuming typeof Ingredient contains properties int ID and string Name, then you view model would be something like

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

    Then the controller

    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
    }
    

    And in the view

    @model RecipeViewModel
    @using(Html.BeginForm())
    {
      ....
      @Html.ListBoxFor(m => m.SelectedIngredients, Model.IngredientList)
      ....
    }
    
    0 讨论(0)
提交回复
热议问题