我们正在为基本网站制定一些可访问性标准,如果用户名字段未通过模型中定义的验证,则需要将焦点返回到用户名字段。我读过几篇文章,表明这是存在的行为。但是,这不是我们看到的行为。我对 mvc natice 功能持开放态度(我们使用带有 razor 的 mvc 3)或 jquery)
最佳答案
I have read several posts that indicate this is the behavior as it exists
奇怪,你这些帖子在哪里?我建议您通知此类帖子的作者,这不是默认行为。
当然,当某些东西不是默认行为时,如果你想实现它,你就必须实现它。例如,您还没有准确指定如果存在多个错误,它应该如何表现:应该关注哪个字段?首先?第三?第七个?
假设您想要首先关注。假设您使用 jQuery,您可以将以下内容添加到您的 View 中:
@if (!ViewData.ModelState.IsValid)
{
var key = ViewData
.ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => x.Key)
.FirstOrDefault();
if (!string.IsNullOrEmpty(key))
{
<script type="text/javascript">
$(function () {
$(':input[<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3bdb2beb6ee939ba7bebffd81b2a4" rel="noreferrer noopener nofollow">[email protected]</a>(Json.Encode(key))]').focus();
});
</script>
}
}
这样你就差不多完成了。嗯,几乎,此代码的进一步改进当然是将其外部化为可重用的 HTML 帮助器,以避免将您的 View 转换为绝对可怕的东西。例如,您可以有一个自定义助手来实现此行为,您所要做的就是将以下内容添加到您的 _Layout
中:
@Html.FocusOnFirstError()
可以通过以下方式实现:
public static class HtmlExtensions
{
public static IHtmlString FocusOnFirstError(this HtmlHelper htmlHelper)
{
if (htmlHelper.ViewData.ModelState.IsValid)
{
return MvcHtmlString.Empty;
}
var key = htmlHelper
.ViewData
.ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => x.Key)
.FirstOrDefault();
if (string.IsNullOrEmpty(key))
{
return MvcHtmlString.Empty;
}
var script = new TagBuilder("script");
script.Attributes["type"] = "text/javascript";
script.InnerHtml = string.Format(
"$(function() {{ $(':input[name={0}]').focus(); }});",
Json.Encode(key)
);
return new HtmlString(script.ToString(TagRenderMode.Normal));
}
}
关于asp.net-mvc-3 - MVC 3 现场验证始终关注失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10709267/