Tab Order in ASP.NET MVC 3 Helpers
Asked Answered
S

5

12

How can I use Tab Order property for following code:

<td>
    @Html.EditorFor(model => model.Cost)                
</td>

I tried this:

<td tabindex=1>
    @Html.EditorFor(model => model.Cost)                
</td>

any suggestions?

Sinkhole answered 13/7, 2011 at 12:39 Comment(1)
The last time SO has seen @AbdullahSaqib was 5 days after this question was asked in 2011Metic
K
14

You can also specify the same html attribute in the helper itself as follows.

@Html.TextBoxFor(model => model.Cost, new { tabindex = 1 })
Kinesthesia answered 29/9, 2011 at 3:18 Comment(3)
This does not work in EditorFor, a second parameter in EditorFor of type object is used to build View Data not add HTML attributes per the documentation: msdn.microsoft.com/en-us/library/ff406462.aspxSiren
You can't specify additional parameters in the EditorFor.Metic
Sorry, I think I was using TextBoxFor and just replaced the helper name thinking EditorFor would work the same way.Kinesthesia
M
10

As a contrast to @Stuy1974's right answer, if you don't want to leave the EditorFor solution, you're going to have to wire up your own Editor Template.

@ModelType SomeApp.ViewModels.SomeNiftyViewModel 

// be sure to include the TabIndex info in the ViewModel
@Html.TextBoxFor(model => model.Cost, new { tabindex = model.TabIndex })

You can also use the ViewData parameter already passed to the editor template directly rather than adding the tab index to the model:

// In the main view
@Html.EditorFor(model => model.Cost, new { TabIndex = 3 })

// In the editor template
@{ int tabIndex = (ViewData["TabIndex"] as int?) ?? 0; }
@Html.TextBoxFor(model => model, new { tabindex = tabIndex })
Metic answered 14/2, 2012 at 1:46 Comment(0)
J
1

Simply do this

@Html.EditorFor(model => model.Cost,  new { htmlAttributes = new { tabindex = 34 } })
Jerryjerrybuild answered 29/7, 2014 at 10:55 Comment(0)
M
1

Another option, allowing you to retain the EditorFor, is to set the tab index in javascript after the page has loaded with something like:

var myEditorFor = document.getElementById("MyEditorForId");

if (myEditorFor != null) {
    myEditorFor.setAttribute("tabindex","18")
}
Myke answered 22/10, 2015 at 17:9 Comment(0)
S
0

Unfortunately @Html.EditorFor method doesn't provide the ability to add HTML attributes. You can add these via a more specific method call. In the above case I'd use -

@Html.TextBoxFor(model => model.Cost, new { tabindex = 1 })

Singhalese answered 14/2, 2012 at 1:38 Comment(1)
He doesn't have to move away from the EditorFor. He could just as easily create an Editor Template.Metic

© 2022 - 2024 — McMap. All rights reserved.