Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to model bind with a foreach loop in asp.net MVC4?

While researching this question I have found a reliable way to bind a list property.

See examples here:

  • https://stackoverflow.com/a/14157016/3229947
  • https://stackoverflow.com/a/6585642/1099260

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?

like image 302
D1v3 Avatar asked Jan 11 '23 06:01

D1v3


1 Answers

@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

like image 111
Rajshekar Reddy Avatar answered May 31 '23 19:05

Rajshekar Reddy