Modelbinding IEnumerable in ASP.NET MVC POST?

女生的网名这么多〃 提交于 2019-12-04 02:30:46

Model binding depends upon how generated html looks like. for ur particular scenario to bind properly html should look like

<input type="text" name = "ResponseInfo.SubsetInfo.BandAvailabilities[0].BandName"/>
<input type="text" name = "ResponseInfo.SubsetInfo.BandAvailabilities[1].BandName"/>
<input type="text" name = "ResponseInfo.SubsetInfo.BandAvailabilities[2].BandName"/>
.
.
<input type="text" name = "ResponseInfo.SubsetInfo.BandAvailabilities[n].BandName"/>

i have not tried it but i am almost certain that call to ToArray method in loop is keeping the system from generating proper names for nested inputs. There are couple of things you can do to remedy this First, in your view model change

public IEnumerable<BandAvailabilityInfo> BandAvailabilities { get; set; }

to

public IList<BandAvailabilityInfo> BandAvailabilities { get; set; }  //or Array

so you don't have to call ToArray method in the loop and proper names are generated for inputs. Second, make an editor template and put it in Editor templates folder either under the current controller or in shared folder's Editor template folder. Make this view accept model of type BandAvailabilityInfo and name of this view should also be BandAvailabilityInfo. then in your main view you only have to replace entire loop with

 <%: Html.EditorFor(m => m.ResponseInfo.SubsetInfo.BandAvailabilities%>

and rest will be handled by framework itself

gdoron

It works fine with the IEnumarble type.
I think the problem is the ToArray you are writing inside the For loop. (It's very not efficient either)
change the for loop to foreach.

See this excellent answer how to achieve it.

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