MVC4 bind model to ICollection or List in partial

橙三吉。 提交于 2019-11-29 11:09:18

You could use the <input... directly like this:

Page:

<table>
    @Html.Partial("_InformationEdit", Model.Information)
</table>

Partial Page:

@for (int i = 0; i < Model.Count(); i++)
{
    <tr>
        <td>
            <input class="text-box single-line" id="Information[@i]Description" name="Information[@i].Description" type="text" value="@Model[i].Description" />
        </td>
    </tr>
}

Or, to be able to pass the prefix as in your example you could keep the Page code the same and change your partial like:

Page:

<table>        
    @Html.Partial("_InformationEdit", Model.Information, 
        new ViewDataDictionary(Html.ViewDataContainer.ViewData) 
        {
            TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Information" }
        })
</table>

Partial Page:

@for (int i = 0; i < Model.Count(); i++)
{
    <tr>
        <td>
            @{
                string fieldName = string.Format("{0}[{1}].Description", ViewData.TemplateInfo.HtmlFieldPrefix, i);
                <input class="text-box single-line" id="@fieldName" name="@fieldName" type="text" value="@Model[i].Description" />
            }
        </td>
    </tr>
}

Changing my partial to

@model IList<myProject.Models.SomeData>

@{
    var Information = Model;
}

@for (int i = 0; i < Information.Count(); i++)
{
    <tr>
        <td>
            @Html.EditorFor(modelItem => Information[i].Description)
        </td>
    </tr>
 }

Works, but this seems a bit odd!

I guess ensuring that the object being bound is of the same name as the property it needs to be bound to does some wizardry... Other suggestions or explanations are welcome!

your partial should be:

@model IList<myProject.Models.SomeData>

@for (int i = 0; i < Model.Count(); i++)
{
  <tr>
    <td>
      @Html.EditorFor(model => model[i].Description)
    </td>
  </tr>
}

also it's easier to read if you replace i by the item name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!