-->

Tab Order in ASP.NET MVC 3 Helpers

2019-04-19 15:01发布

问题:

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?

回答1:

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

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


回答2:

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 })


回答3:

Simply do this

@Html.EditorFor(model => model.Cost,  new { htmlAttributes = new { tabindex = 34 } })


回答4:

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")
}


回答5:

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 })