MVC3 Razor model binder and legacy collections

I hope that I don’t miss something incredibly obvious, but is there a reason why the connecting device always has difficulty linking a view model that inherits from the collection?

Suppose I want to show a paged list and display a combo box and add a button above it (dealing with simple lists). The classes you enter will look like this:

public class PagedList<T> : List<T> { public int TotalCount { get; set; } } 

And then a view model that looks like this:

 public class MyViewModel : PagedList<ConcreteModel> { public IEnumerable<ChildModel> List { get; set; } public int? SelectedChildModelId { get; set; } } 

So in the view (Razor):

 @model MyViewModel @using (Html.BeginForm()) { @Html.DropDownListFor(model => model.SelectedChildModelId, new SelectList(Model.List, "ChildModelId", "DisplayName")) } 

And the action of the HttpPost controller:

 public ActionResult(MyViewModel viewModel) { ... } 

The above will cause the viewModel in the ActionResult to be null. Is there a logical explanation for this? From what I can say, it is specific only for viewing models that inherit from collections.

I know that I can get around it with a custom binder, but the properties associated with it are primitive types, and there aren’t even any generics or inheritance.

I redesigned view models to inherit the type of the collection as properties and fix the problem. However, I am still scratching my head why the binder is breaking on it. Any constructive thoughts appreciated.

+6
source share
2 answers

To answer my own question: all my models that have something to do with collections no longer inherit from a general list or the like, but instead have the property of the type of collection they want. This works much better, because when rendering you can use

 @Html.EditorFor(m => m.CollectionProperty) 

And create your own editor in the Views / Shared / EditorTemplates section for the contained type. It also works great with the binder model, since all the individual elements from the collection receive an index, and the binder can automatically bind it when sent.

Lesson learned: If you plan to use models in views, do not inherit them from collection types.

+1
source

Sometimes linking a model to a collection works better if the data in the form message is formatted differently.

I am using a plugin called postify.

http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/

0
source

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


All Articles