ASP.NET MVC CheckBox List发送始终为null

时间:2016-12-14 14:57:10

标签: asp.net-mvc html-helper

我想创建一个包含项目和复选框的表格来选择这些项目。我将这些复选框包含在列表中,但此列表始终返回null。非常感谢你的帮助。

控制器:

public ActionResult Index()
{
    var expenseTypesView = new ViewExpenseTypesAndSelection
    {
        ExpensesTypes = _context.ExpenseType.ToList(), 
    };       
    return View(expenseTypesView);
}

[HttpPost]
public ActionResult SelectExpensesTypes( ViewExpenseTypesAndSelection SelectedExpenses)
{
    var entry = new userSpecificExpenses();
    var i = 0;
    foreach (var item in SelectedExpenses.SelectedExpenses)
    {
        if(item)
        {
            entry.expenseTypeId = i;
            entry.UtilisateurId= User.Identity.GetUserId();
            _context.UserspecificExpenses.Add(entry);
            _context.SaveChanges();
        }
        i++;
    }
    return View();
}

查看:

@model MBT.ViewModels.ViewExpenseTypesAndSelection
....
@using (Html.BeginForm("SelectExpensesTypes", "ExpenseTypes"))
{
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th class="text-center">Expense</th>
                <th class="text-center">Include</th>
            </tr>
        </thead>
        <tbody>
            @{
                for (int i = 0; i < Model.ExpensesTypes.Count; i++)
                {
                    <tr>
                        <td>
                            <div class="checkbox">
                                @Model.ExpensesTypes[i].Type
                            </div>
                        </td>
                        <td>
                            <div class="checkbox">
                                @Html.CheckBoxFor(m => m.SelectedExpenses[i])
                            </div>
                        </td>
                    </tr>
                }
            }
        </tbody>
    </table>
    <button type="submit" class="btn btn-primary">Submit</button>
}

1 个答案:

答案 0 :(得分:0)

您使用ViewExpenseTypesAndSelection发送ExpensesTypes几乎为空,然后将其发回给您的帖子方法。这意味着您发送null并接收null。 那有什么问题?