ASP.NET MVC Dynamic List Binding
I have a strongly typed mvc page which I wont to bind a unorder list to a list of objects. So in mvc view it might look something like
<% foreach (var item in Model.WhatYouDoL) { %>
<li><%: Html.Encode(item.Text) %><input type="hidden" name="WhatYouDoL[0].Reference" /></li>
<% } %>
My view model might look something like
public class ViewModelQuoteWhatYouDoInMotorTrade
{
开发者_开发技巧 public List<WhatYouDo> WhatYouDoL { get; set; }
}
and my list contains object like
public struct WhatYouDo
{
public decimal Percent { get; set; }
public string Reference { get; set; }
public string Text { get; set; }
}
This binds ok providing I use WhatYouDoL[0].Reference with the index ([0]) which when loading I can set with an index. The problem is I want to add and remove from this list on the client side. So I might have some js which adds and extra list item and removes the current. This means I have to somehow manage the indexes in the name and keep them in order and non duplicate on the client side. Does anyone know if there is a way to get around using the index in the name.
Thanks in advance.
There is, probably, a mistake:
<% foreach (var item in Model.WhatYouDoL) { %>
<li><%: Html.Encode(item.Text) %><input type="hidden" name="WhatYouDoL[0].Reference" /></li>
<% } %>
Maybe it should be:
<% foreach (var item in Model.WhatYouDoL) { %>
<li><%: item.Text %><input type="hidden" name="<%: item.Reference %>" /></li>
<% } %>
You don't need to encode as long as you use <:
proof
精彩评论