且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以绑定在asp.net MVC4 foreach循环模型?

更新时间:2023-02-16 17:23:13

  @foreach(时期Model.PeriodList期)
        {
            < D​​IV> @ Html.TextBoxFor(U => period.PeriodStartNumber)LT; / DIV>
            < D​​IV> @ Html.TextBoxFor(U => period.PeriodEndNumber)LT; / DIV>
        }

在这里什么是发生的,假设你有PeriodList 3价值观和循环执行3次,现在来到 @ Html.TextBoxFor(U => period.PeriodStartNumber)这部分创建具有命名一个文本框 PeriodStartNumber 或有时 period.PeriodStartNumber 的MVC将值绑定到模型中的HTML元素的标签名称必须与你的模型字段(你也有3个文本框具有相同的名称 - >如果你想induvidually值绑定这是不好的)。所以现在我侦察你没有在名称PeriodStartNumber模型中的字段,但你有PeriodList即。有一个在DOM与名称PeriodList没有元素得到你的模型属性绑定所以MVC不会绑定。

只要保持在控制器后采取行动的参数如

 公众的ActionResult SomeAction(型号基于myModel,字符串[] PeriodStartNumber)
{
}

您将有值绑定到PeriodStratNumber。

注意: 重要的是要知道在与MVC播放。始终确保在HTML元素标记名称和模型字段名称是相同的。只有这样的结合将MVC完成

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