Search code examples
asp.net-mvclistmodelbindersviewdata

Modelbinding lists


I got a controller action like

public class Question {   
   public int Id { get;set; }
   public string Question { get;set; }
   public string Answer { get;set; } 
}

public ActionResult Questions() 
{   
  return View(GetQuestions()); 
}

public ActionResult SaveAnswers(List<Question> answers) 
{  
  ... 
}

the view> looks like:

<% for (int i = 0; i < Model.Count; i++) { %>   
 <div>
  <%= Html.Hidden(i.ToString() + ".Id") %>
  <%= Model[i].Question %>
  <%= Html.TextBox(i.ToString() + ".Answer") %>
 </div> 
<% } %>

Obviously this view doesn't work. I'm just not able access the list in the view.

The documentation for this also is outdated, it seem a lot of the functionality around modelbinding lists where changed in the beta.


Solution

  • the answer is not to use the html helpers.

    <% for (int i = 0; i < Model.Count; i++) { %> 
      <div>
         <input type="hidden" name="answers[<%= i %>].Id" id="answers_<%= i %>_Id" value="<%= Model[i].Id %>" />
         <input type="text" name="answers[<%= i %>].Answer" id="answers_<%= i %>_Answer" value="<%= Model[i].Answer %>" />
      </div> 
    <% } %>
    

    Not very pretty, but works. The important thing is that Name and Id need to be different. Name is allowed to have "[", "]" but id isn't.