Question

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.

Was it helpful?

Solution 3

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.

OTHER TIPS

I think that Scott Hanselman's post probably holds the answer. However it appears that you are trying to tie you view references to an anonymous object by returning in the post ...0.Answer=answer...

You should instead I believe be tying your fields to the `List answers refering to the answers[index].Answer.

Try the following:

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

Richard

Take a look at this and this question. Also this blog post.

Edit : As for accessing the model in the view. Are you sure you declared your with the following attribute?

<%@ Page Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<List<Namespace.Question>>" %>
//Assuming the GetQuestions() method returns a list of question objects.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top