Skip to main content
 首页 » 编程设计

c#之将 listboxfor 发送到 Controller

2024年02月06日13unruledboy

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

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

这是我认为的列表框:

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

此行给出一个错误,即列表必须包含 SelectListItem。即使我更改为那个,并在我的 View 模型中更改它,它仍然不起作用。

这是我的 View 模型:

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

这是我的 Controller :

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

我想要的是在 Controller 中,我希望模型列表成分由 View 中列表框中的所有项目/值填充,但我无法弄清楚。

请您参考如下方法:

多选回传一组简单值(例如 [1, 4, 7] 或 ["Recipe 2", "Recipe 4"] 取决于所选选项的值)。您不能将 ListBoxFor 绑定(bind)到复杂对象的集合。您的 View 模型需要具有要绑定(bind)的属性。假设 typeof Ingredient 包含属性 int ID 和 string Name,那么您的 View 模型将类似于

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

然后是 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 
} 

在 View 中

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