views:

1213

answers:

2

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.

+1  A: 

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.

Derek Lawless
+3  A: 

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 inp = $('.input-validation-error:first').get(0);
       if (inp) inp.focus();
    });
</script>
tvanfosson