模型绑定两个或多个集合

时间:2010-12-11 15:34:38

标签: asp.net-mvc

有没有人使用Phil Haack发布的代码绑定两个或更多集合的运气模型:Model Binding To A List

例如,我有以下代码。

public class Book {
  public string Name { get; set; }
}
public class Author {
  public string Name { get; set; }
}


public ActionResult Index(List<Book> books, List<Author> authors) {
  // Will never model bind two collections.
}

我拥有的HTML是:

<input type="hidden" name="books.index" value="1" />
<input type="text" name="books[1].Name" />

<input type="hidden" name="books.index" value="2" />
<input type="text" name="books[2].Name" />

<input type="hidden" name="authors.index" value="1" />
<input type="text" name="authors[1].Name" />

<input type="hidden" name="authors.index" value="1" />
<input type="text" name="authors[1].Name" />

我得到的例外是:

  

参数字典包含'HomeController'中方法'System.Web.Mvc.ActionResult Index(System.Collections.Generic.List 1[Book], System.Collections.Generic.List 1 [作者])'的参数'authors'的无效条目。字典包含类型'System.Collections.Generic.List 1[Book]', but the parameter requires a value of type 'System.Collections.Generic.List 1 [作者]'的值。参数名称:参数

我是做错了还是ASP.NET MVC不支持?

1 个答案:

答案 0 :(得分:3)

你的问题在别的地方,我无法重现。以下工作对我来说很好:

型号:

public class Book
{
    public string Name { get; set; }
}
public class Author
{
    public string Name { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(List<Book> books, List<Author> authors)
    {
        return View();
    }
}

查看:

<% using (Html.BeginForm()) { %>
    <input type="text" name="books[0].Name" value="book 1" />
    <input type="text" name="books[1].Name" value="book 2" />

    <input type="text" name="authors[0].Name" value="author 1" />
    <input type="text" name="authors[1].Name" value="author 2" />

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

它成功地将值绑定在POST操作中。


更新:

我确认这是bug in ASP.NET MVC 3 RC2,它将在RTM中修复。作为解决方法,您可以将以下内容放入Application_Start

ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();