Question

I have a model with an property of type icollection.

public class myClass{
   public string param1{get; set;}
   public string param2{get; set;}
   public virtual ICollection<myClass2> param3{get; set;}

   public myClass()
   {
       param3 = new hashSet<myClass2>();
   }

}

public class myClass2{
   public string param4{get; set;}
   public string param5{get; set;}
   public virtual myClass param6{get; set;}
}

I pass the model containing these two class to my view and am able to see the items in my icollection by using foreach(var item in Model.myClass.param3)

And I store the items in a hidden field to retrieve it in my controller

foreach(var item in Model.myClass.param3){
      @Html.HiddenFor(model => item.parm4);
      @Html.HiddenFor(model => item.parm5);
 }

But when I submit the form and pass the model to the controller, I get a count = 0 when calling model.myClass.param3.

How can I pass an ICollection to my view? I tried this link but do not know why it is not working.

EDIT

The link uses the class Book as a list in order to index (suggesting I should cast the ICollection to a list). How do I do that? Also, if I cast it to a list how do i pass that to the controller as the controller expects to receive an ICollectiion?

Was it helpful?

Solution

You can't use a foreach loop for that, you have to use a for loop.

for (int i=0; i<Model.MyClass.param3.Count; i++)
    {
        @Html.HiddenFor( model => model.MyClass.param3[i])
    }

The reason for this is the HiddenFor helper needs some way of assigning unique names to each field for the model binding to work. The i variable accomplishes this.

In your case you;ll need to do some refactoring to implement this. I don't think ICollection or HashSet supports indexing, so you'll need to cast it to a List or some collection that does support indexing.

See this excellent blog post on the subject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top