EditorFor ignores tabindex. How do you set a tabindex?

RobLeather picture RobLeather · Feb 17, 2011 · Viewed 13.4k times · Source

The use of tabindex seems to only work for htmlhelpers like Textboxfor and not EditorFor

For example;

<%: Html.TextBoxFor(model => Model.MyItem, new { @tabindex = "3" })%>

Produces a tabindex value.

However, if you use;

<%: Html.EditorFor(model => Model.MyItem, new { @tabindex = "3" })%>

Then the result is that the control is created as expected, but the tabindex is missing.

So...... How is it possible to set the tabindex for a given EditorFor control?

Answer

RobLeather picture RobLeather · Feb 18, 2011

The main problem I was having is that I needed to create a EditorFor type mechanism in order to format the decimal like a currency (our system has multiple currencies so "C" would not have been appropriate), get a tab index working AND allow the system to maintain the standard validation.

I've managed to achieve that using the following. By creating my own custom editor control.

Create a file (mine is called decimal.ascx) within the Views/Shared/EditorTemplates directory of your project.

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<decimal?>" %>
 <% int intTabindex = 0;
   decimal myVal = 0;

   string strModelValue = "";
   if (Model != null)
   {
       myVal = (decimal)Model;
       strModelValue = myVal.ToString("#.00");
   }
   else
       strModelValue = "";



   if (ViewData["tabindex"] != null)
   {
       intTabindex = (int)ViewData["tabindex"];
   }
 %>
 <%: Html.TextBox("", strModelValue, new { @tabindex = intTabindex })%>

Essentially, this code just overrides what would normally be presented in a "decimal" EditorFor method with the;

<%: Html.TextBox("", Model.ToString("#.00"), new { @tabindex = intTabindex }) %>

template.

My calling code now reads;

<%: Html.EditorFor(model => Model.MyItem, new { tabindex = 5 })%>

The result is the following code on the page.

<input id="Model_MyItem" name="Model.MyItem" tabindex="5" type="text" value="12.33" />

Which is exactly what I required.

Whilst this is only true for my particular circumstances, I would encourage anybody looking to solve this issue to attempt a custom control first for the task as it might save you a considerable amount of time.

If would of course be possible in the code to create a specific type of control required and adjust the results around that.

For example; we could simple add another item in the call to determine the text format.

new {tabindex = 12, numberformat=2}

Then simply create a handler for all the formats.