集中关注 ASP.NET MVC 模型错误 [英] Set focus on on ASP.NET MVC model errors

查看:24
本文介绍了集中关注 ASP.NET MVC 模型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型可以进行一些验证检查并将错误添加到 ModelState:

I've got a model that does some validation checking and adds the errors to ModelState:

ViewData.ModelState.AddModelError("mycontrol", "message")

它们在视图端显示良好,但是有没有办法将焦点设置到与验证消息对应的控件上?现在,页面会刷新并停留在页面顶部,因此如果错误发生在页面的末尾,用户并不知道发生了什么.

They display fine on the view side, but is there a way to set the focus to the control that corresponds to the validation message? Right now, the page refreshes and stays at the top of the page, so if the error is towards the end of the page, it's not obvious to the user what happened.

注意:另一种解决方案是让 ValidationSummary 在页面顶部显示错误列表,但我一直无法让它显示任何内容.我所有的错误都通过 ValidationMessage 显示.

Note: Another solution would be for ValidationSummary to show the list of errors at the top of the page, but I've never been able to get it to display anything. All my errors are displayed via ValidationMessage.

我发现 ValidationSummary 有问题.我的标记是:

I found my problem with ValidationSummary. The markup I had was:

<% Html.ValidationSummary()%>

应该是:

<%=Html.ValidationSummary()%>

我仍然想知道如何捕捉到有错误的字段.

I'd still like to know how to snap to the field with the error however.

推荐答案

滚动到第一个输入错误的一些 jquery 优点.棘手的一点是,您必须在调用 focus() 之前获取底层 DOM 元素,因为 jQuery 对象上的 focus() 方法会触发 focus 事件,而不是将焦点放在元素上.

Some jquery goodness to scroll to the first input with an error. The tricky bit is that you have to get the underlying DOM element BEFORE you invoke focus() as the focus() method on a jQuery object fires the focus event instead of giving focus to the element.

<script type='text/javascript'>
    $(document).ready( function()
    {
       var input = $('.input-validation-error:first');

       if(input)
       {
           input.focus();
       }
    });
</script>

这篇关于集中关注 ASP.NET MVC 模型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆