Html Asp.NET将选中项目的列表传递给控制器

Html Asp.NET将选中项目的列表传递给控制器,html,asp.net,web,checkbox,Html,Asp.net,Web,Checkbox,我在这里遗漏了一些东西。我有一个带有复选框的项目表,我希望能够从中选择项目,然后将选中项目列表发送给控制器。我无法将任何内容传递给控制器。我想要一个可以在控制器中使用的列表或数组 以下是我所拥有的: @model Recipe2Grocery.ViewModels.GroceryListViewModel @{ ViewBag.Title = "Index"; } @section Scripts{ <style type="text/css"> t

我在这里遗漏了一些东西。我有一个带有复选框的项目表,我希望能够从中选择项目,然后将选中项目列表发送给控制器。我无法将任何内容传递给控制器。我想要一个可以在控制器中使用的列表或数组

以下是我所拥有的:

@model Recipe2Grocery.ViewModels.GroceryListViewModel

@{
    ViewBag.Title = "Index";
}
@section Scripts{
    <style type="text/css">
        table {
            color: white;
        }
</style>
}

<div style="margin: 20px;">
@using (Html.BeginForm("Index", "RecipeIngredient", FormMethod.Post))
{
    <table class="table">
        <tr>
            <th></th>
            <th>
                Quantity
            </th>
            <th>
                IngredientName
            </th>
            <th>
                Category
            </th>
            @foreach (var item in Model.ShoppingList)
            {
            <tr>
                <td>
                    @Html.CheckBoxFor(modelItem => item.IsChecked)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Ingredient.Quantity)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Ingredient.IngredientName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Ingredient.Category)
                </td>
            </tr>
            }
        </table>
        <input type="submit" />
}

首先,您的视图无法工作。你的型号是什么?如果它是一个列表,那么
@Html.DisplayNameFor(…)
将无法工作。否则,您无法在模型上迭代。究竟是什么问题?它是否引发错误?抱歉,编辑:模型的类型为:@model IEnumerableand,错误是未向控制器传递任何内容。您应该将
bool
属性添加到
RecipeCredit
模型,然后呈现
@Html.CheckboxFor(modelItem=>item.CheckedProperty)
。它将输出一组正确配置的复选框,这些复选框将发送到控制器(post操作应接收一个
IEnumerable
)。
public class ListItem
{
    public bool IsChecked { get; set; }
    public RecipeIngredient Ingredient { get; set; }

    public ListItem()
    {
        Ingredient = new RecipeIngredient();
    }
}

public class GroceryListViewModel
{
    public List<ListItem> ShoppingList { get; set; }

    public GroceryListViewModel()
    {
        ShoppingList = new List<ListItem>();
    }
}
[HttpPost]
    public ActionResult Index(GroceryListViewModel vm)
    {
        // blah
        return RedirectToAction("Index", "Home");
    }