Aximili
Aximili

Reputation: 29444

ASP.NET MVC 2: How do you use Html.EditorFor for custom models?

I am wondering how this would work in MVC 2.

Suppose I want to render a view (Popup.ascx) that has a list of questions, I created these ViewModels

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

I would have a method like this in the controller

[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 - What would I put in the view Popup.ascx? Do I need a BeginForm here?

<%@ 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" />

This is my view for 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 - Then how do I get the values back when the user hit the submit button?

Thanks in advance.

Upvotes: 0

Views: 610

Answers (1)

David Neale
David Neale

Reputation: 17018

I'd accept a parameter of IEnumerable<VMQuestion> on the POST action.

You will need to add an index to the properties of each VMQuestion for the default model binder to bind the collection. See this article: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Upvotes: 1

Related Questions