chfumero
chfumero

Reputation: 1147

How to show server side validations errors on asp.net mvc using Ajax

I know that this is a very common question but I can't find any one that solve my problem.

I am using Asp.net mvc5. I am making an Ajax call using the helpers that provide asp. The code in the template looks like this.

@using (Ajax.BeginForm("Register", "Account",null , new AjaxOptions
        {
            HttpMethod = "POST",
            Url = "/Account/Register/",
            OnSuccess = "onSuccess"
        }))
        { 

<p>@Html.ValidationMessage("Register.Email")</p>
@Html.TextBox("Email", null, new { placeholder = "Enter your email")
 <input type="submit" value="submit" />

}

My problem here is that I want to show the validations errors that come from the server using the ajax callback, without re-rendering the page.

Now my question is. How must I write the action on the controller to handle this problem automatically? By automatically I mean what is the way to return something on the controller action that populates the error fields when the model is not valid.

Any help will be appreciated, thanks.

Upvotes: 2

Views: 997

Answers (1)

hutchonoid
hutchonoid

Reputation: 33326

If you add the model state errors as a key value pair in your controller you can use the below method to display them.

JavaScript

This finds all the validation message spans with model state error keys and adds the red error message to them. Please note you may want to adapt this to display many error messages against a key.

public doValidation(e)
{
        if (e.data != null) {
            $.each(e.data, function (key, value) {
                $errorSpan = $("span[data-valmsg-for='" + key + "']");
                $errorSpan.html("<span style='color:red'>" + value + "</span>");
                $errorSpan.show();
            });
        }
}

View

Add the OnFailure parameter that points to the newly created doValidation javascript method. The argument e is automatically passed across from the json result. This doValidation can be called from within any of your javascript methods, so you may want to call it from onSuccess too.

{
    HttpMethod = "POST",
    Url = "/Account/Register/",
    OnSuccess = "onSuccess",
    OnFailure = "doValidation"
}

Upvotes: 2

Related Questions