我有一个视图模型,其中包括一组复选框。当我的控制器的后置方法绑定时,我需要复选框来映射到一个数组。
这是视图模型。
@model TMDM.Models.TestSeriesCreateviewmodel @{ ViewBag.Title = "Create"; } <h2>Create a Test Series</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <h3>Which Test Collections are in this Test Series?</h3> <div class="editor-field"> @{ var i = 0; foreach (var testCollection in Model.TestCollections) { <input type="checkBox" id="ChosenTestCollectionIds[@i]" name="ChosenTestCollectionIds[@i]" value="@testCollection.Id" /> <span>@testCollection.Title</span> <br /> i++; } } </div> <p> <input type="submit" value="Save" class="medium green awesome" /> @Html.ActionLink("Cancel","Index","TestSeries",null,new { @class = "medium black awesome" }) </p> </fieldset>
表单呈现正常,我已经检查了源代码,每个输出复选框的id和name字段都有不同的数字。
<input type="checkBox" id="ChosenTestCollectionIds[0]" name="ChosenTestCollectionIds[0]" value="5" /> <input type="checkBox" id="ChosenTestCollectionIds[1]" name="ChosenTestCollectionIds[1]" value="6" /> //etc...
这是视图模型。
public class TestSeriesModel { public int Id { get; set; } public string Title { get; set; } } public class TestSeriesCreateviewmodel : TestSeriesModel { public List<ITestCollectionDataObject> TestCollections { get; set; } public int[] ChosenTestCollectionIds { get; set; } }
我遇到的问题是,当表单发回ChosenTestCollectionIds数组时,返回null。我在这里做错了什么?
回答
我已经弄清楚如何做:
<input type="checkBox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" />
解决方法
<input type="checkBox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" />