Run MVC Remote Validation Synchronously

764 views Asked by At

I am using MVC's built in Remote Validation to validate a form on the server side.

My modelview looks like this:

[Required(ErrorMessage = "{0} is required")]
[Remote ("ValidateUserID", "MyController", AdditionalFields = "AccountType", ErrorMessage = "{0} cannot be found.")]
[Display(Name = "Account")]
public string Account { get; set; }

Typically my remote validation is nearly instant, however rarely it gets caught up and will take nearly 1 or 2 seconds to finish. This causes a problem with my form.

Some of my other fields are based on whether or not the Account field is valid or not.

So I need to force this remote validation to run synchronously.

Before you say it, I know it freezes the page. But I am okay with this. If you guys can give me any better ideas that is also greatly appreciated.

Thanks!

2

There are 2 answers

0
fdomn-m On

If you can give me any alternative ideas

You could use a simple jquery-ui dialog with text "Please Wait..." (or something specific such as "Validating...") and an animated image.

Show the dialog just before the post and close it when you get a response.

If you're using unobtrusive validation, you'll need to add this:

$("form").bind("invalid-form.validate", function () {
    // hide 'please wait' 
});

Additional options are to show this via a timeout so it's only shown when the post takes more than a short time and to use some form of fadein (not sure if possible with a dialog), then you don't get the annoying flash on the times it's very quick.

Another choice would to be apply a translucent overlay (eg opacity 80%) just over the form div (rather than a dialog over the whole page). This works well if you have multiple panels/sections on your page - eg to cover up your other fields while the account field is validated remotely.

0
AudioBubble On

This is controlled by the remote: function(value, element, param) { method in the jquery.validate.js file, which makes an ajax call and uses the default async: true.

You could modify this file (add async: false,) but I would not recommend that. Instead you could remove the [Remote] and then handle the .change() event of the input to make your own ajax call to the controller with async: false,.