代码之家  ›  专栏  ›  技术社区  ›  AndreasN

模型绑定列表

  •  0
  • AndreasN  · 技术社区  · 17 年前

    我有一个控制器的动作像

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

    视图>看起来像:

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

    显然,这种观点行不通。我只是无法访问视图中的列表。

    这方面的文档也过时了,似乎有很多关于modelbinding列表的功能在beta版中发生了更改。

    3 回复  |  直到 17 年前
        1
  •  0
  •   Richbits    17 年前

    我认为Scott Hanselman的职位可能持有答案。但是,您似乎试图通过在帖子中返回来将视图引用与匿名对象绑定在一起 ...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> 
    <% } %>
    

    理查德

        2
  •  0
  •   Community Mohan Dere    9 年前

    看看 this this question . 而且 this blog post .

    编辑: 至于在视图中访问模型。您确定使用以下属性声明了您的属性吗?

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

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

    不是很漂亮,但很管用。重要的是名字和Id必须不同。 名称允许有“[”,“]”,但id不允许。