【问题标题】:ASP.NET MVC 2: How do you use Html.EditorFor for custom models?ASP.NET MVC 2:如何将 Html.EditorFor 用于自定义模型?
【发布时间】:2011-01-23 22:37:23
【问题描述】:

我想知道这将如何在 MVC 2 中工作。

假设我想渲染一个包含问题列表的视图 (Popup.ascx),我创建了这些 ViewModels

  public class VMPopup
  {
    public List<VMQuestion> Questions;
  }
  public class VMQuestion
  {
    public int Id
    public string Question;
    public string Answer;
    public bool Mandatory;
  }

我会在控制器中有这样的方法

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Popup(int elementId)
{
  List<VMQuestion> questions = new List<VMQuestion>();

  // Code to generate the questions
  // .....

  VMPopup vm = new VMPopup{Questions = questions};
  return View(vm);
}

1 - 我将在视图 Popup.ascx 中放入什么?我在这里需要一个 BeginForm 吗?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EnterpriseConnectMVC.Controllers.VMPopup>" %>

    <table border="1">
      <% foreach(var q in Model.Questions) { %>
        <%= Html.EditorFor(q); // I know this is wrong, how should I do it? %> 
      <% } %>
    </table>

    <input type="submit" value="OK" />

这是我对 VMQuestion 的看法

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EnterpriseConnectMVC.Controllers.VMQuestion>" %>

<tr>
  <td><%= Model.Question %></td>
  <td>
    <%= Html.TextBoxFor(m=>m.Answer) %>
    <%= Html.ValidationMessageFor(m=>m.Answer) %>
  </td>
</tr>

2 - 那么当用户点击提交按钮时如何取回这些值?

提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-2 html-helper


    【解决方案1】:

    我会在 POST 操作中接受 IEnumerable&lt;VMQuestion&gt; 参数。

    您需要为每个VMQuestion 的属性添加一个索引,以便默认模型绑定器绑定集合。见这篇文章:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多