0

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.

peter pan
  • 281
  • 4
  • 14

1 Answers1

0

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

Community
  • 1
  • 1
The Smallest
  • 5,713
  • 25
  • 38
  • don't forget colon in <% item.Reference %>, I think it should be <%: item.Reference %> – zam6ak Dec 02 '10 at 18:40
  • Hi, thanks for taking the time to answer. I might not have put my question across properly. The problem is having to use this naming convention name="WhatYouDoL[0].Reference". I want to add and remove to the list client side but this means i need to make sure at the end all the [0] indexes are correct in the collection. I was hoping o could do name="WhatYouDoL.Reference" and mvc would work out it is a collection. Thanks again. – peter pan Dec 02 '10 at 21:26
  • I think this might work. I havent tried it yet though. Non sequential indexes part. http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx – peter pan Dec 03 '10 at 09:59
  • I think this might work. http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx – peter pan Dec 03 '10 at 15:23