Set focus on an EditorFor without the use of JavaS

2019-02-08 17:32发布

问题:

Is it possible to set the focus on the following code on a page load without the use of JavaScript?

<div class="col-md-10">
    @Html.EditorFor(model => model.Description)
    @Html.ValidationMessageFor(model => model.Description)
</div>                

回答1:

Your can use the autofocus attribute. Refer documentation

@Html.TextBoxFor(model => model.Description, new { autofocus = "autofocus" })

The equivalent for EditorFor (using MVC-5.1+ only) is obtained with the following syntax:

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { autofocus = "autofocus" } })


回答2:

You can add id to your div and pass this id int the end of the url of your page:

<div class="col-md-10" id="description">
    @Html.EditorFor(model => model.Description)
    @Html.ValidationMessageFor(model => model.Description)
</div>

http://site/page#description