Model 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) 
{  
  ... 
}

view> is as follows:

<% 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 does not work. I just can't access the list in the view.

The documentation for this is also outdated, it seems to have a lot of functionality in the model binding lists, which were changed in the beta version.

0
source share
3 answers

the answer is not to use 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 beautiful, but it works. The important thing is that the name and identifier must be different. The name is allowed to have "[", "]", but id is not.

0
source

. .

: . , ?

<%@ Page Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<List<Namespace.Question>>" %>
//Assuming the GetQuestions() method returns a list of question objects.
0

, , , . , , ...0.Answer=answer...

, " ", [index].Answer.

:

<% 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> 
<% } %>

0

Source: https://habr.com/ru/post/1712262/


All Articles