tags:

views:

41

answers:

1

My web form contains list of dynamic fields that are generated like this:

<% for (int i = 0; i < Model.Options.Count; i++) { %>
...
    <%= Html.Hidden("Options[" + i + "].Id", Model.Options[i].Id)%>
    <%= Html.CheckBox("Options[" + i + "].Selected", Model.Options[i].Selected)%>
...

This maps perfectly on array of controller method parameters as described in Model Binding To A List article.

I want to add label for checkboxes to title them, but I have to guess their ids in hmtl layout.

Options[" + i + "].Selected turns into Options_0__Selected

So I add code like this:

<label for="Option_<%=i%>__Selected"><%: Model.Option[i].Title%></label>

How can I avoid hardcoding Id generation in-built asp.net mvc rules?

Thank you advance.

+1  A: 

You could achieve this using editor templates - no more magic strings:

<%= Html.EditorFor(x => x.Options) %>

And then you place a Option.ascx in the Views/Shared/EditorTemplates folder:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<YourNamespace.Option>" %>

<%= Html.HiddenFor(x => x.Id) %>
<%= Html.LabelFor(x => x.Selected) %>
<%= Html.CheckBoxFor(x => x.Selected) %>
Darin Dimitrov
Interesting. I'll take a closer look. Thank you.
Andrew Florko