IEnumerable视图在HttpPost上返回null

时间:2013-09-08 18:00:06

标签: asp.net asp.net-mvc razor

我有一个Form,其中包含CheckBoxesDisplayField类似网格的结构。 我想用Checked CheckBoxes获取行。 问题我在Controller's post方法中变为空。
模型

public class RegisterModuleSelection 
{
    [Display(Name = "ID")]
    public int mID { get; set; }

    [Display(Name = "Module")]
    public string Module { get; set; }

    [Display(Name = "Buy")]
    public bool Buy { get; set; }        
}

查看

@model IEnumerable<MAK_ERP.Models.RegisterModuleSelection>
@{
ViewBag.Title = "Register - Modules Selection";}
<h2>
Register - Modules Selection</h2>
@using (Html.BeginForm("RegisterModules", "UserAccount", FormMethod.Post, new { id = "RegisterModules", @class = "generalForm" }))
{
<table class="Grid Module">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Module)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Duration) (Months)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Buy)
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.HiddenFor(modelItem => item.mID)
                @Html.DisplayFor(modelItem => item.Module)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.EditorFor(modelItem => item.Duration)
            </td>
            <td>
                @Html.CheckBoxFor(modelItem => item.Buy)
            </td>
        </tr>
    }
    <tr>
        <td colspan="4">
            <input type="submit" value="Next" class="button3" />
            <input type="reset" value="Reset" class="button4" />
        </td>
    </tr>
</table>
}

控制器

   [HttpGet]
    public ActionResult RegisterModules()
    {
        IEnumerable<MAK_ERP.Models.RegisterModuleSelection> model = reg.getModules();
        return View(model);
    }
    [HttpPost]
    public ActionResult RegisterModules(IEnumerable<Models.RegisterModuleSelection> regMod)
    {
    //regMod is null here
    ...

2 个答案:

答案 0 :(得分:2)

不幸的是你无法以这种方式绑定。 Model binding depends upon how generated html looks like.在这种特殊情况下,它应该类似于:

<input id="item_Buy" type="checkbox" value="true" name="item[0].Buy" checked="checked">

如果您对一些变通方法没问题,可以使用for循环而不是foreach循环,您可以在其中为每个控件名称添加索引,模型绑定器可以正确绑定它们。

有一些非常有用的讨论,你可以在这里查看:ASP.NET MVC - Insert or Update view with IEnumerable model。还有Model Binding To A List。另一个是:Modelbinding IEnumerable in ASP.NET MVC POST?

答案 1 :(得分:0)

您应该使用EditorTemplates来解决问题。

ASP.NET MVC Multiple Checkboxes上接受的答案会对您有所帮助。

相关问题