【问题标题】:Modelbinding lists模型绑定列表
【发布时间】:2009-10-12 22:00:44
【问题描述】:

我有一个控制器动作,比如

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

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

这方面的文档也已经过时了,似乎很多模型绑定列表的功能在测试版中都发生了变化。

【问题讨论】:

    标签: asp.net-mvc list modelbinders viewdata


    【解决方案1】:

    我认为 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】:

      看看thisthis 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】:

      答案是不使用 html 助手。

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

      不是很漂亮,但很有效。重要的是 Name 和 Id 需要不同。 名称可以有“[”、“]”,但 id 不能。

      【讨论】:

        猜你喜欢
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多