Reputation: 421
I have two classes and the first one contains a List. The VIEW receives a List as a model. When I post the view I'm able to retrieve in the controller each simple property. But the List<> is always null for the SubModels.
The two classes:
public class MyModel
{
public int ModelId {get;set;}
public string Description {get;set;}
public List<SubModel> SubModels {get;set;}
}
public class SubModel
{
public int MySubModelId {get;set;}
public string Description {get;set;}
}
In the view page the model received is
@model List<MyModel>
Following recommendations on internet, I created an editorfor editor to render my class in the view:
@model MyModel
<tr id="@Model.ModelId">
@Html.HiddenFor(m => m.ModelId)
@Html.HiddenFor(m => m.Description)
<td>@Model.Description</td>
</tr>
@for(int i = 0; i < Model.SubModels.Count; i++)
{
// How to render the class here to be able to be post in the controller?
// @Html.HiddenFor(m => m.SubModels[i]) will not work of course...
}
Upvotes: 2
Views: 996
Reputation: 421
The answer is: create a EditorFor template for each properties of a class that contains List<> to be able to get it into the controller.
Thank you all for your help because some of you gave me ideas.
Upvotes: 0
Reputation: 165
Just the way you have hidden the Id for the main model, you also need to hide the Id for each of the submodels. Otherwise there is no way for the program to keep track of them. Include the hidden field in the for-loop to cover each submodel.
@Html.HiddenFor(m => m.SubModels[i].MySubModelId)
(If this doesn't fix it, the problem is most likely in your controller and you should post that to hash out other possibilities.)
Upvotes: 0
Reputation:
Unfortunately HiddenFor
does not act recursively, but you can do it by hand:
@for (int i = 0; i < Model.SubModels.Count; i++)
{
// postback everything
@Html.HiddenFor(m => m.SubModels[i].MySubModelId)
@Html.HiddenFor(m => m.SubModels[i].Description)
}
Just posting back MySubModelId
for each submodel would be enough to prevent Model.SubModels
from being null.
Usually I just postback the IDs, reloading everything else within the action method.
Upvotes: 1