ASP.NET MVC 5 Tutorial :: Error Validation on Ajax

ASP.NET MVC 5 Tutorial

In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called “validation rules” “validation constraints” or “check routines”, that check for correctness, meaningfulness, and security of data that are input to the system. The rules may be implemented through the automated facilities of a data dictionary, or by the inclusion of explicit application program validation logic.

hflnet51

If you’re developing rich web clients using Asp.net MVC on the back-end, you’ve probably come across this functionality that can be described with these conditions:

  1. client side data (may be a form),
  2. ajax posting of this data (form),
  3. controller action has strong type parameters,
  4. controller action processes data and returns anything but a full view (since it was an Ajax call)

Familiar? Then you’ve come across this problem: »What should be done when validation fails?«
Seems fairly straight forward, right? Well not so fast my fellow developer friend…

Old Fashioned

Validation in Asp.net MVC is really simple and very transparent. If you had to think about it all the time when developing Asp.net Web forms applications, you don’t have to do that with MVC anymore. Whenever your controller action takes strong type parameters and you define validation rules on the type itself, you can easily just lay back and watch the magic happen in front of your eyes.

When you don’t use Ajax (how old fashioned of you), your form will be posted back the usual way by means of browser reloading the whole page. Because browser reloads the whole page there will be some flickering since it will clear the window at a certain point to render the new response. So your application will have a master view (in terms of master/detail process), where the user could click some Add new link or button that will redirect them to the new entity view (the details view). This view presents a form where they enter relevant data and a button to submit it to server. Your controller action could look very similar to this:

[HttpPost]
public ActionResult Add(Person instance)
{
    if (!this.ModelState.IsValid)
    {
        // return the same view with validation errors
        return View(instance);
    }
    // save the new person instance and go back to master view
    Person result = this.Service.Add(instance);
    return RedirectToAction("Index");
}

Contemporary

But since we’re savvy web developers, we rather use asynchronous processing these days. Instead of asking the browser to post back data and reload the whole page, we rather issue an Ajax call. This way we avoid page flickering and even the nasty long page scroll position stays the same. Ajax FTW! All today’s desktop browsers support this functionality as well. Great way of doing it then.

The whole client process probably changed according to our advanced functionality. We’d still have the master view with the list of all entities, but clicking on the Add new link will most probably present a modal dialog box with the details form instead of redirecting the user to a whole new page. In terms of usability and interface comprehension, this is a much better experience. Something similar is frequently used in Sharepoint 2010 these days. The process would work like this:

  1. User clicks Add new link on the master view.
  2. Your javascript dims the master view and displays a dialog box with the new entity form (details view).
  3. User enters relevant data and clicks the Save link.
  4. Your javascript issues an Ajax call that posts back data.
  5. When everything goes according to the plan, server responds either with a PartialViewResult that holds visual representation of the newly created entity that can be appended to master page entity list, or JsonResult data that can be consumed for the same purpose (but you’ll have to manually transform JSON to visual HTML representation).
  6. Your javascript closes the dialog box.
  7. Master view is in full display again and your javascript adds the newly created entity to it’s list (while also providing some highlight animation).

It’s wiser to return a partial view since the same partial view can be used on the master view to display each entity item in the list, so they will be fully compatible and when you change your partial view, both functionalities still work as expected. Otherwise you’d have to change javascript code as well. Not DRY at all. This is our controller action now:

[HttpPost]
public ActionResult Add(Person instance)
{
    if (!this.ModelState.IsValid)
    {
        // we'll see this in a bit
    }
    // save the new person instance and go back to master view
    Person result = this.Service.Add(instance);
    return PartialView("Person", result); // or Json(result)
}

So what do we do, when user enters incorrect data into the form that’s not valid? You can’t just return some other partial view, because javascript expects something else. You could of course put additional functionality on the client side that would detect different HTML being returned, but that’s very prone to errors. Think of changing the partial view. Any of the two. DRY again. The best thing would actually be to return a 400 HTTP response and provide the right result in it. Why is this better?

  • Because it will keep working even when you completely redesign your views.
  • Because it’s going to be much easier to distinguish between a successful results and an erroneous one on the client.

If you’re an Asp.net MVC developer it’s highly likely that you use jQuery on the client. Distinguishing success from an error cannot be easier:

$.ajax({
    url: "Person/Add",
    type: "POST",
    data: $(this).serializeArray(), // provided this code executes in form.onsubmit event
    success: function(data, status, xhr) {
        // YAY! Process data
    },
    error: function(xhr, status, err) {
        if (xhr.status == 400)
        {
            // this is our erroneous result
        }
        else
        {
            // some other server error must have happened (most probably HTTP 5xx)
        }
    }
});

To make things reusable on the server side you have two possible (and most obvious) ways of doing it:

  1. Provide additional controller extension methods like PartialViewError, JsonError, etc. that will work very similar to their normal counterparts except they’ll also set the response status code to 400 (don’t forget to check whether this is an Ajax call, because if it’s not, don’t set status code).
  2. Provide a custom exception and an exception action filter that handles it.

The first one is quite trivial so I’ve decided to do the latter. And since I don’t use the usual pattern of displaying in-place form validation errors it also suits my needs.

Let’s first look at the code of my custom exception. It’s called ModelStateException because I throw it on invalid model state and it has a constructor that takes model state and gets the errors automatically from it. This is the code of the exception:

/// <summary>
/// This exception that is thrown when there are model state errors.
/// </summary>
[Serializable]
public class ModelStateException : Exception
{
    /// <summary>
    /// Gets the model errors.
    /// </summary>
    public Dictionary<string, string> Errors { get; private set; }
    /// <summary>
    /// Gets a message that describes the current exception and is related to the first model state error.
    /// </summary>
    /// <value></value>
    public override string Message
    {
        get
        {
            if (this.Errors.Count > 0)
            {
                return this.Errors.First().Value;
            }
            return null;
        }
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="ModelStateException"/> class.
    /// </summary>
    public ModelStateException() : base()
    {
        this.Errors = new Dictionary<string, string>();
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="ModelStateException"/> class.
    /// </summary>
    /// <param name="modelState">State of the model.</param>
    public ModelStateException(ModelStateDictionary modelState)
        : this()
    {
        if (modelState == null)
        {
            throw new ArgumentNullException("modelState");
        }
        //this.ModelState = modelState;
        if (!modelState.IsValid)
        {
            StringBuilder errors;
            foreach (KeyValuePair<string, ModelState> state in modelState)
            {
                if (state.Value.Errors.Count > 0)
                {
                    errors = new StringBuilder();
                    foreach (ModelError err in state.Value.Errors)
                    {
                        errors.AppendLine(err.ErrorMessage);
                    }
                    this.Errors.Add(state.Key, errors.ToString());
                }
            }
        }
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="ModelStateException"/> class.
    /// </summary>
    /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
    /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// The <paramref name="info"/> parameter is null.
    /// </exception>
    /// <exception cref="T:System.Runtime.Serialization.SerializationException">
    /// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
    /// </exception>
    protected ModelStateException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
        if (info == null)
        {
            throw new ArgumentNullException("info");
        }
        // deserialize
        this.Errors = info.GetValue("ModelStateException.Errors", typeof(Dictionary<string, string>)) as Dictionary<string, string>;
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="ModelStateException"/> class.
    /// </summary>
    /// <param name="message">The message.</param>
    public ModelStateException(string message)
        : base(message)
    {
        this.Errors = new Dictionary<string, string>();
        this.Errors.Add(string.Empty, message);
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="ModelStateException"/> class.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The inner exception.</param>
    public ModelStateException(string message, Exception innerException)
        : base(message, innerException)
    {
        this.Errors = new Dictionary<string, string>();
        this.Errors.Add(string.Empty, message);
    }
    /// <summary>
    /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about the exception.
    /// </summary>
    /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
    /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic).
    /// </exception>
    /// <PermissionSet>
    ///     <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/>
    ///     <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/>
    /// </PermissionSet>
    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
        {
            throw new ArgumentNullException("info");
        }
        // serialize errors
        info.AddValue("ModelStateException.Errors", this.Errors, typeof(Dictionary<string, string>));
        base.GetObjectData(info, context);
    }
}

The exception action filter has to intercept ModelStateException exceptions and return the error in a predefined format, so the client’s able to uniformly consume it. This is the code that I’m using:

/// <summary>
/// Represents errors that occur due to invalid application model state.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public sealed class HandleModelStateExceptionAttribute : FilterAttribute, IExceptionFilter
{
    /// <summary>
    /// Called when an exception occurs and processes <see cref="ModelStateException"/> object.
    /// </summary>
    /// <param name="filterContext">Filter context.</param>
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        // handle modelStateException
        if (filterContext.Exception != null && typeof(ModelStateException).IsInstanceOfType(filterContext.Exception) && !filterContext.ExceptionHandled)
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = 400;
            filterContext.Result = new ContentResult {
                Content = (filterContext.Exception as ModelStateException).Message,
                ContentEncoding = Encoding.UTF8,
            };
        }
    }
}

Reusable End Result

All our controller actions can now take advantage of this reusable functionality. The previously shown controller action now looks like this:

[HttpPost]
[HandleModelStateException]
public ActionResult Add(Person instance)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }
    // save the new person instance and go back to master view
    Person result = this.Service.Add(instance);
    return PartialView("Person", result);
}

Our client side functionality can now be packed into a simple application specific jQuery plugin that does ajax error handling and can be loaded as part of the general scripts on your master (as in master template) view:

$.extend({
    appAjax: function(url, type, datagetter, onsuccess) {
        /// <summary>jQuery extension that executes Ajax calls and handles errors in application specific ways.</summary>
        /// <param name="url" type="String">URL address where to issue this Ajax call.</param>
        /// <param name="type" type="String">HTTP method type (GET, POST, DELETE, PUT, HEAD)</param>
        /// <param name="datagetter" type="Function">This parameterless function will be called to return ajax data.</param>
        /// <param name="onsuccess" type="Function">This optional function(data) will be called after a successful Ajax call.</param>
        var execSuccess = $.isFunction(onsuccess) ? onsuccess : $.noop;
        var getData = $.isFunction(datagetter) ? datagetter : function() { return datagetter; };
        $.ajax({
            url: url,
            type: type,
            data: getData(),
            error: function(xhr, status, err) {
                if (xhr.status == 400)
                {
                    alert(xhr.responseText);
                }
                else
                {
                    alert("Server error has occured.");
                }
            },
            success: function(data, status, xhr) {
                window.setTimeout(function() {
                    execSuccess(data);
                }, 10);
            }
        });
    }
});

In your page, you can simply call it this way:

$.appAjax(
    "Person/Add",
    "POST",
    function() { return $(this).serializeArray(); },
    function(data) { // consume data }
);

This is the reusable model validation in Asp.net MVC applications using Ajax calls and jQuery on the client side.

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24×7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality – beyond other hosting control panels – and ease of use, Plesk Control Panel is available only to HostForLIFE’s customers. They offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.

image

Posted in Hosting Tutorial and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , .