A model linking two or more collections

Has anyone had any good luck model linking two or more collections using the code posted by Phil Haack here: binding a model to a list ?

As an example, I have the code below.

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 I have:

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

Exception I get:

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

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

+3
1

, . :

:

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.


UPDATE:

, ASP.NET MVC 3 RC2, ​​ RTM. Application_Start:

ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
+3

Source: https://habr.com/ru/post/1779749/


All Articles