title: How to use a required data annotation for a list of textboxes
body: <p>I have a form with multiple values for a custom question. The idea being a user can make their own custom question with custom answers. One of the properties of the Model object is a list of objects:</p>
  
  <pre><code>public class CustomQuestion
  {
      public int Id { get; set; }
      [Required]
      public string QuestionName{ get; set; }
      public virtual List&lt;CustomQuestionAnswer&gt; Answers { get; set; }
  
  }
  
  public class CustomQuestionAnswer
  {
      public int Id { get; set; }
      [Required]
      public string Answer { get; set; }
  
  }
  </code></pre>
  
  <p>Now I have this in razor which works to create the answers (I have omitted the rest of the question):</p>
  
  <pre><code>foreach (var answer in Model.Answers)
  {
      if (answer.IsActive)
      {
          &lt;div class="form-group answer"&gt;
              &lt;div class="col-md-10"&gt;
                  @Html.Hidden("answers[" + count + "].Id", answer.Id)
                  @Html.TextBox("answers[" + count + "].Answer", answer.Answer, new { @class = "form-control" })
                  validation code will go here
              &lt;/div&gt;
              &lt;div class="col-md-2"&gt;
                  @Html.CheckBox("answers[" + count + "].IsActive", answer.IsActive)
             &lt;/div&gt;
         &lt;/div&gt;
         count++;
      }
  }
  </code></pre>
  
  <p>Now everything is working fine and saving to the database, except the data validation is not working. I have the data validation messages working for the CustomQuestion's QuestionName (so I know it is not an issue of jquery loading properly), but not for the answers. I have tried putting these lines in the razor form:</p>
  
  <pre><code>@Html.ValidationMessageFor(m =&gt; answer.Answer, "", new { @class = "text-danger" })
  @Html.ValidationMessage("Answers[" + count + "].Answer", "", new { @class = "text-danger" })
  </code></pre>
  
  <p>But neither works. Also, when I click on the save button, I get this error message in the browser console:</p>
  
  <pre><code>Failed to load resource: the server responded with a status of 400 ({"Answers[0].Answer":["The Answer field is required."]})
  </code></pre>
  
  <p>Any ideas as to what I need for the validation code?</p>