Set focus on on ASP.NET MVC model errors

后端 未结 2 545
太阳男子
太阳男子 2021-01-02 09:39

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

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


        
相关标签:
2条回答
  • 2021-01-02 10:01

    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>
    
    0 讨论(0)
  • 2021-01-02 10:19

    You could use JavaScript to find the input elements on the page that have the MVC validation HTML class (input-validation-error) added, and move the carat to the first one. That /should/ move the screen to that element although I haven't tested it.

    A JS library such as jQuery will make this straightforward to do.

    0 讨论(0)
提交回复
热议问题