I am totally at a loss here and can’t find a solution to this problem. Can somebody please help provide some code to either:
- Allow [] to be used so as to save contained collection within a @model?
- Somehow map/bind a contained collection from within a model (I have read Phil Haack’s Collection binding blog but this isn’t a flat collection being passed in….I already have a model A coming in?
- I have also tried setting up a new view model (contains model classes A and B from below) but my model is coming back null in the httppost (even if I add a simple string type like “Name” and bind it…comes back null). I’m sure there AutoMapper issues that I am not aware of.
I’m a complete newbie with mvc3. Here are the details…
Edit View:
@model MVC3.Models.A
// I need to save collection values but can't use [] here to setup model binding.
// I have read about mapping collections but I already have a model A that is getting passed in.
//
@Html.EditorFor(model => model.Bs[0].Val)
Models:
public class A
{
public A()
{
this.Bs = new HashSet<B>();
}
public int Name { get; set; }
public virtual ICollection<B> Bs { get; set; } // Can't change this to ILIst because of above HashSet
- }
public class B
{
public int Val { get; set; }
public virtual A A { get; set; }
}
Your model has circular references in your view models. That’s not a supported scenario by the default model binder. I would recommend you to always use editor templates in your views. Example:
Model:
Controller:
View (
~/Views/Home/Index.cshtml):Corresponding editor template which will be rendered for each element of the Bs collection (
~/Views/Home/EditorTemplates/B.cshtml):