title: Validating MVC Data Collections
body: <p>I have a simple Question data model:</p>
  
  <pre><code>public class Question {
      int QuestionId { get; set; }
      string Text { get; set; }
      string Answer { get; set; }
      string ValidationMessage { get; set; }
  };
  </code></pre>
  
  <p>Using this class I have built a view Model:</p>
  
  <pre><code>public class QuestionViewModel {
      string Introduction { get; set; }
      IEnumerable&lt;Question&gt; Questions { get; set; }
  };
  </code></pre>
  
  <p>My Controller the  builds the view model (from a data source) and renders the view:</p>
  
  <pre><code>@model QuestionViewModel
  
  @using (Html.BeginForm()) {
      if (Model.Questions != null) {
          &lt;ol&gt;
              @Html.EditorFor(m =&gt; Model.Questions)
          &lt;/ol&gt;
      }
      @Html.ValidationSummary("Unable to process answers...")
  
      &lt;input type="submit" value="submit" /&gt;
  }
  </code></pre>
  
  <p>This view utilises an EditorTemplate:</p>
  
  <pre><code>@model Question
  
  &lt;li&gt;
      @Html.HiddenFor(m =&gt; m.Questionid)
      @Html.TextBoxFor(m =&gt; m.Answer)
      @Html.ValidationMessageFor(m =&gt; m.Answer)
  &lt;/li&gt;
  </code></pre>
  
  <p>For now, when the page is posted back, the controller validates the response:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Response(QuestionViewModel model) {
      if (ModelState.IsValid) {
         for (int i = 0; i &lt; model.Questions.Count(); i++) {
             Question q = model.Questions[i];
             string questionId = String.Format("Questions[{0}]", i);
  
             if (String.IsNullOrWhiteSpace(q.Answer)) {
                 ModelState.AddModelError(questionId, q.ValidationMessage);
             }
         }
      }
  }
  </code></pre>
  
  <p>The problem I'm having is that most of this works fine - the validates and the Validation Summary shows the correct validation messages.  The problem is that I can't get individual field validators to render the error:</p>
  
  <pre><code>&lt;span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Questions[0].StringValue"&gt;&lt;/span&gt;
  </code></pre>
  
  <p>As you can see, when I call the ModelState.AddModelError() method, I am currently using key value of the format "Questions[0]", but I have also tried "Questions_0" and various other combinations.</p>
  
  <p>Any help/guidance would be much appreciated.</p>
  
  <p>[Apologies for the overly long post]</p>