发送列表框给控制器 [英] Send listboxfor to controller
问题描述
我的视图中有一个包含列表框的表单.用户将值添加到列表框中.
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 be placed in my models property that is a List.
这是我视图中的列表框:
Here is the Listbox in my view:
@Html.ListBoxFor(m => m.Ingredients, new List<Ingredient>(), new { @class = "form-control" , @id = "Ingredients"})
此行给出一个错误,即列表必须包含SelectListItem.即使我更改为该视图,并且在我的视图模型中也进行了更改,它仍然不起作用.
This line gives an error that is that the List has to contain SelectListItem. Even if i change to that, and also change it in my view model, it still doesn't work.
这是我的视图模型:
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));
}
我想要的是在控制器中,我希望模型列表成分"由视图中列表框中的所有项目/值填充,但我无法弄清楚.
What I want is that in the controller, I want the models List Ingredients to be populated by all the items/values in the listbox from the view but I cant figure it out.
推荐答案
多选回发简单值数组(例如[1, 4, 7]
或["Recipe 2", "Recipe 4" ]
取决于所选选项的值).您不能将ListBoxFor
绑定到复杂对象的集合.您的视图模型需要具有要绑定的属性.假设typeof Ingredient
包含属性int ID
和string Name
,那么您查看模型的过程将类似于
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; }
}
然后是控制器
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)
....
}
这篇关于发送列表框给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!