开发者

Model binding two or more collections

开发者 https://www.devze.com 2023-01-30 06:32 出处:网络
Has anyone had any luck model binding two or more collections using the code posted by Phil Haack here: Model Binding To A List?

Has anyone had any luck model binding two or more collections using the code posted by Phil Haack here: Model Binding To A List?

As an example, I have the below code.

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

The HTML that I have is:

<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=开发者_JAVA技巧"text" name="authors[1].Name" />

The exception that I get is:

The parameters dictionary contains an invalid entry for parameter 'authors' for method 'System.Web.Mvc.ActionResult Index(System.Collections.Generic.List1[Book], System.Collections.Generic.List1[Author])' in 'HomeController'. The dictionary contains a value of type 'System.Collections.Generic.List1[Book]', but the parameter requires a value of type 'System.Collections.Generic.List1[Author]'. Parameter name: parameters

Am I doing something wrong or is this not supported by ASP.NET MVC?


Your problem is somewhere else, I was unable to reproduce. The following works fine for me:

Model:

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

Controller:

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

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

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

It successfully binds values back in the POST action.


UPDATE:

I confirm that this is a bug in ASP.NET MVC 3 RC2 which will be fixed in the RTM. As a workaround you could put the following in your Application_Start:

ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
0

精彩评论

暂无评论...
验证码 换一张
取 消