Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC - Can't bind array to view model
    primarykey
    data
    text
    <p>I have a view model with a from that includes a set of checkboxes. I need the check boxes to map to an array when binding in the post back method of my controller.</p> <p>Here's the view model.</p> <pre><code>@model TMDM.Models.TestSeriesCreateViewModel @{ ViewBag.Title = "Create"; } &lt;h2&gt;Create a Test Series&lt;/h2&gt; @using (Html.BeginForm()) { @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Title) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Title) @Html.ValidationMessageFor(model =&gt; model.Title) &lt;/div&gt; &lt;h3&gt;Which Test Collections are in this Test Series?&lt;/h3&gt; &lt;div class="editor-field"&gt; @{ var i = 0; foreach (var testCollection in Model.TestCollections) { &lt;input type="checkbox" id="ChosenTestCollectionIds[@i]" name="ChosenTestCollectionIds[@i]" value="@testCollection.Id" /&gt; &lt;span&gt;@testCollection.Title&lt;/span&gt; &lt;br /&gt; i++; } } &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Save" class="medium green awesome" /&gt; @Html.ActionLink("Cancel", "Index", "TestSeries", null, new { @class = "medium black awesome" }) &lt;/p&gt; &lt;/fieldset&gt; </code></pre> <p>The form is rendering fine, I've checked the source and each output check box has a different number for their id and name fields.</p> <pre><code>&lt;input type="checkbox" id="ChosenTestCollectionIds[0]" name="ChosenTestCollectionIds[0]" value="5" /&gt; &lt;input type="checkbox" id="ChosenTestCollectionIds[1]" name="ChosenTestCollectionIds[1]" value="6" /&gt; //etc... </code></pre> <p>Here is the view model.</p> <pre><code>public class TestSeriesModel { public int Id { get; set; } public string Title { get; set; } } public class TestSeriesCreateViewModel : TestSeriesModel { public List&lt;ITestCollectionDataObject&gt; TestCollections { get; set; } public int[] ChosenTestCollectionIds { get; set; } } </code></pre> <p>Problem I'm having is that when the form posts back the ChosenTestCollectionIds array comes back null. What am I doing wrong here?</p> <p><strong>ANSWER</strong></p> <p>I've worked out how to do it:</p> <pre><code>&lt;input type="checkbox" id="[@i]" name="ChosenTestCollectionIds" value="@testCollection.Id" /&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload