views:

397

answers:

2

How can I set the tabindex value of a set of checkboxes within a foreach loop in ASP.NET MVC?

My current solution uses a Response.Write to output the checkboxes, but I'd rather find something more elegant.

Does anyone have a good solution?

This code does not work:

<label for="country">
    Country:
</label>
<%= Html.DropDownList("country", Model.Countries.OrderBy(x => x.Text), "Choose country...", new { tabindex = 8 })%><br />

<fieldset id="sales-processing-methodologies">
    <legend>Sales Processing Methodology:</legend>
    <% int i = 9;
    foreach (var method in Model.ProcessingMethodologies)
    {
    %>
        <input type="checkbox" id="<%=method.Key%>" name="processing-methodologies" class="checkbox" value="<%=method.Key%>" tabindex="<%i.ToString();%>"> </input>
        <label for="<%=method.Key%>">
            <%=method.Value%>
        </label>
    <% i++;
    } %>
 </fieldset>

This does:

<label for="country">
    Country:
</label>
<%= Html.DropDownList("country", Model.Countries.OrderBy(x => x.Text), "Choose country...", new { tabindex = 8 })%><br />

<fieldset id="sales-processing-methodologies">
    <legend>Sales Processing Methodology:</legend>
    <% int i = 9;
    foreach (var method in Model.ProcessingMethodologies)
    {
        Response.Write(@"<input type=""checkbox"" id=""" + method.Key + @""" name=""processing-methodologies"" class=""checkbox"" value=""" + method.Key + @""" tabindex=""" + i.ToString() + @"""> </input><label for=""" + method.Key + @""">" + method.Value + @"</label>");
        i++;
    } %>
</fieldset>

Edit: The code that wasn't working produced tabindex="".

A: 

Just use a for loop.

Garry Shutler
+5  A: 

I just do a dry-compile (in my brain) and nothing much wrong is with your code. Please post the compiler error here as well.

The only one thing that is wrong is:

<input type="checkbox" id="<%=method.Key%>" name="processing-methodologies" class="checkbox" value="<%=method.Key%>" tabindex="<%i.ToString();%>"> </input>

The tabindex="<%=i.ToString();%>" is missing the equal sign.

xandy
I think you meant tabindex="<%=i.ToString()%> (no semicolon), and it looks like that solved the problem. I thought I needed to use <% since I was calling a method on the integer. Before I made this change, it was just outputting 'tabindex="".' Thanks for the help!
AlexWalker