Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on on ASP.NET MVC model errors

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.

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.

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

<% Html.ValidationSummary()%>

which should have been:

<%=Html.ValidationSummary()%>

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

like image 473
gfrizzle Avatar asked Apr 07 '09 13:04

gfrizzle


2 Answers

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>
like image 195
tvanfosson Avatar answered Nov 16 '22 01:11

tvanfosson


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.

like image 20
derek lawless Avatar answered Nov 16 '22 01:11

derek lawless