While researching this question I have found a reliable way to bind a list property.
See examples here:
Unfortunately, iterating through a list doesn't give me all of the functionality I need.
This code sample performs well for a Get
@foreach (Period period in Model.PeriodList)
{
<div> @Html.TextBoxFor(u => period.PeriodStartNumber) </div>
<div> @Html.TextBoxFor(u => period.PeriodEndNumber) </div>
}
But the values in these controls won't bind on a Post and and I'm left unable to update my model.
Is this a limitation of the framework and thus impossible?
@foreach (Period period in Model.PeriodList)
{
<div> @Html.TextBoxFor(u => period.PeriodStartNumber) </div>
<div> @Html.TextBoxFor(u => period.PeriodEndNumber) </div>
}
What happens here is , Suppose your PeriodList had 3 values and loop is executed 3 times, Now coming to the @Html.TextBoxFor(u => period.PeriodStartNumber)
part this creates a text box with the NAME PeriodStartNumber
or sometimes period.PeriodStartNumber
for MVC to bind values to your model the html element tag name must match to your model field (and you also have 3 textboxes with the same name -> this is not good if you want to bind values induvidually). SO now I recon you dont have a field in your model with name PeriodStartNumber But you have PeriodList ie. there is no element with name PeriodList in the DOM to get binded with your model property so MVC will not bind it.
Just keep a parameter in controller post action like
public ActionResult SomeAction(Model myModel, string[] PeriodStartNumber )
{
}
you will have the values binded to PeriodStratNumber.
Note: Important thing to know while playing with MVC. Always make sure the Html element tag name and the model field name are the same. Only then binding will be done by MVC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With