EditorFor的自动对焦功能

10

我想在我的应用程序中使用自动对焦来编辑器,但似乎无法实现。我已经成功地在文本框上使用了自动对焦,但我想使用编辑器以保持我的应用程序的通用外观。

任何解决方案都将不胜感激,谢谢。

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

@DavidG 是的,我也尝试过那个。 - Jon
4个回答

13
由于您使用的是 EditorFor,而不是像 TextBoxFor 这样的具体控件。
@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { 
                    @class = "form-control" }, autofocus="autofocus"})

你也可以使用jQuery来实现这个功能:

<div class="editor-field focus">
    @Html.EditorFor(model => model.Description)
    @Html.ValidationMessageFor(model => model.Description)
</div> 
$(function() {
    $('.focus :input').focus();
});
更新:
正如您所知,TextBoxFor总是创建一个类型为输入的文本框,但EditorFor有点聪明,它根据属性的数据类型呈现标记。

你是说为了使用自动对焦,输入数据类型不能存在歧义? - Jon
@Jon 如果您查看EditorFor的重载,就会发现没有任何重载接受htmlAttributes。您正在使用的重载实际上是使用additionalViewData。 - Sirwan Afifi
谢谢,我对asp.net还比较新,还没有学习太多的jQuery知识,但是你的jQuery解决方案完美地解决了我的问题。 - Jon

9

使用 .Net Framework 4.5 和 MVC 5,这个对我很有效:

@Html.EditorFor(model => model.Description, new {
    htmlAttributes = new {
        @class = "form-control",
        autofocus = true
    }
})

3
您把自动对焦属性放错了位置。
@Html.EditorFor(model => model.Description, 
     new { htmlAttributes = new { @class = "form-control" }, autofocus = "" })

请尝试这个替代方法:
@Html.EditorFor(model => model.Description, 
     new { htmlAttributes = new { @class = "form-control", autofocus = "" } })

1

我一直在关注这个帖子,也许我已经找到了关于EditorFor自动对焦的答案——这都是Asp.Net 4.5和MVC 5,不过这并不重要。

  1. 在Scripts文件夹中我有一个jQuery脚本文件:

    $(function(){ $('.someclassname').focus(); });

我将脚本名称添加到BundleConfig中,并在视图中呈现它。

  1. 在视图中,我将类名添加到EditorFor <div class="col-md-10" someclassname">
  2. 然后我将 type="text" autofocus="autofocus" 添加到EditorFor的 @class 中。所以,new{@class="form-control", type="text", autofocus="autofocus"
  3. 就这样,当DOM加载时,.someclassname字段获得光标焦点...... PS. 实际上,如果只做(3)也可以......

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接