Error handling in ASP.NET MVC

This is a basic error handling strategy for an ASP.NET MVC app. It will handle all ASP.NET errors, allow somewhere to put logging code and redirect to a generic error page.

This will miss exceptions not handled by ASP.NET such as navigating to an invalid URL but will be sufficient to handle and log application errors in your controllers.

First start by creating an ErrorController (this one is basic but could be expanded):

using System.Web.Mvc;

namespace BasicErrorHandling.Controllers
{
    public class ErrorController : Controller
    {
        // GET: Error
        public ActionResult Index(string message)
        {
            TempData["errorMessage"] = message;
            return View();
        }
    }
}

Don’t forget to create a view for said controller:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error</title>
</head>
<body>
    <div> 
        <h1>Generic Error Page</h1>
        <p>@TempData["errorMessage"]</p>
        
    </div>
</body>
</html>

For testing purposes, let’s introduce an exception in one of our actions:

public ActionResult About()
{
    ViewBag.Message = "Your application description page.";

    // throw an error to test exception handling
    throw new Exception("Fictious error");

    return View();
}

The method that will handle our errors and redirect to our error page is in our Global.asax.cs:

protected void Application_Error(object sender, EventArgs e)
{
    // get error and clear it 
    var exception = Server.GetLastError();
    Server.ClearError();

    // log error
    // ...

    // redirect to error page
    string message = Regex.Replace(exception.Message, @"\t|\n|\r", ""); // replace newlines which will not work with query string
    Response.Redirect("/Error/?message=" + message);
}

Here we should log or handle the error in the manner appropriate to our application. Finally we redirect to an error page supplying an optional message parameter. We could also redirect to this error controller from somewhere else than Global.asax.

To make everything work nicely we need to add a new route in our RouteConfig.cs:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Error",
        url: "Error/{message}", 
        defaults: new { controller = "Error", 
                        action = "Index", 
                        message = UrlParameter.Optional } 
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", 
                        action = "Index", 
                        id = UrlParameter.Optional }
    );
}

 
You can find the whole thing on GitHub.

Simple Ajax scenario in ASP.NET MVC Part 3: graceful degradation

This follows part 1 and part 2.

Let’s continue improving our previous example by adding more requirements. This time supporting clients without JavaScript aka graceful degradation for our Ajax feature.

Graceful degradation in web design refers to supporting less capable clients correctly. In our case, using Ajax will currently only work in browsers with JavaScript enabled.

While that is most browsers, the best scenario possible is to support all browsers, even those who have disabled JavaScript or do not support it.

Supporting clients without JavaScript is sometimes required for conforming to standards or for accessibility reasons.

Changing our previous example

If we disable JavaScript and try our current version of our example application our filtering feature doesn’t work anymore (as well as our jQuery DataTables plugin).

jsdisabled

We are currently using the onclick event on a checkbox. Since this won’t submit the form without JavaScript we need to show the input element we had hidden in Part 2 when JS is disabled.

We still want to have that element hidden if JavaScript is enabled so instead of relying on style=”display: none” we will use JavaScript to hide the input element.

using (Ajax.BeginForm("FilterDepartmentsAjax",
                       new AjaxOptions
                       {
                           HttpMethod = "POST",
                           InsertionMode = 
                               InsertionMode.Replace,
                           UpdateTargetId = 
                               "department-table",
                           OnSuccess = "tableUpdated",
                       }))
{
    <label>Filter: </label>
    @Html.CheckBoxFor(model => model.Filtered, 
                      new { onclick = "$(this).parents('form:first').find(':submit')[0].click();" })
    <input id="input-filter" type="submit" value="Submit" />
}

<div id="department-table">
    @{ Html.RenderPartial("DepartmentsTablePartial", Model); }    
</div>

@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#input-filter').hide();
            $('#deparment-table').DataTable();
        });

        function tableUpdated() {
            $('#deparment-table').DataTable().draw();
        }
    </script>    
}

Now our button is shown only when JavaScript is disabled.

The next problem is that we want to return a PartialView when we are dealing with an Ajax request and a View when we are dealing with a regular request.

Otherwise we will either get only the partial view with JavaScript disabled or loose our jQuery DataTables functionality when we return a whole view.

The correct this we change the FilterDepartmentsAjax method return type to ActionResult and use if (Request.IsAjaxRequest()) like so:

[HttpPost]
public ActionResult FilterDepartmentsAjax(
                       DepartmentsModel model)
{
    var updatedModel = new DepartmentsModel
    {
        Filtered = model.Filtered,
        Departments = GetDepartments(model.Filtered),
    };

    if (Request.IsAjaxRequest())
        return PartialView("DepartmentsTablePartial", 
                           updatedModel);

    return View("Index", updatedModel);
}

Problem solved.

You can find the whole project on GitHub and the specific changeset for this blog post.

 

Simple Ajax scenario in ASP.NET MVC Part 2: integrating jQuery DataTables with our Ajax call

This follows part 1.

My previous example of filtering a table was pretty basic. Let’s complicate things a little bit. While online examples are often simplistic, programming a real application isn’t.

Let’s integrate the common jQuery DataTables plugin to our table. Doing so will provide many functionalities but will break our last example.

Let’s see how and what we can do to fix it.

First install jQuery DataTables. You can get the NuGet package, download the files online and include them manually in your project or link to the CDN.

For the sake of simplicity I will link to the CDN in my _Layout.cshtml file.

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, 
          initial-scale=1.0">
    <title>@ViewBag.Title - ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <link rel="stylesheet" 
          type="text/css" 
          href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css">

And later in this same file…

    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript" 
            charset="utf8" 
            src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js">
    </script>
    @Scripts.Render("~/bundles/bootstrap")

Now let’s call the plugin on the page with our existing table by adding this at the end of Index.cshtml:

@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#deparment-table').DataTable();
        });
    </script>    
}

And adding an id to our table in our DepartmentsTablePartial.cshtml partial view.

<table id="deparment-table" class="table table-striped">

As we can see we now have a full featured data table with filtering, sorting and paging.

datatables1

Sadly when we make our Ajax call to get all the data instead of a filtered subset we loose the DataTables functionalities.

datatables2

This is because jQuery DataTables isn’t aware of our Ajax update. We are rewriting the content inside the div but we aren’t making the plugin aware of this fact. Luckily there is a function available in the plugin API to handle that scenario.

We need to change our Ajax Helper BeginForm call to include an OnSuccess function:

@using (Ajax.BeginForm("FilterDepartmentsAjax",
               new AjaxOptions
               {
                   HttpMethod = "POST",
                   InsertionMode = InsertionMode.Replace,
                   UpdateTargetId = "department-table",
                   OnSuccess = "tableUpdated",
               }))

And our Scripts section will now contain a tableUpdated function.

<script type="text/javascript">
    $(document).ready(function () {
        $('#deparment-table').DataTable();
    });

    function tableUpdated() {
        $('#deparment-table').DataTable().draw();
    }
</script>    

It might be counter-intuitive that we aren’t using the Ajax functions of DataTables but this is because we our handling the Ajax call through our MVC controller. The MVC Ajax Helper is already updating the table and we just want DataTables to take notice of it.

DataTables ajax.reload() expect a JSON data source and we have none to give it. We simply want to data table to redraw itself.

If we start out site again everything is now working:

datatables3

As before you can find the code on GitHub here and the specific change set here.

Simple Ajax scenario in ASP.NET MVC: filtering a table

I will present a very simple example of how to use Ajax in ASP.NET MVC. In this example we will filter a grid by making an Ajax request. Here is what the result will look like:

table

I have started by creating a new ASP.NET MVC project in Visual Studio 2015.

newproject

The first step is to add the Microsoft.jQuery.Unobstrusive.Ajax package via NuGet:

nugetajax

Once this package has been added, modify your BundleConfig.cs file located in App_Start to add the jquery.unobtrusive-ajax.js file to the jQuery bundle (or another bundle of your choice).

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js",
            "~/Scripts/jquery.unobtrusive-ajax.js"));

This bundle is referenced by default in the _Layout.cshtml file in the default project created by Visual Studio. If you aren’t using this default project template, add the bundle to your layout or your page.

Next I create two model classes in the project:

namespace Ajax2.Models
{
    public class DepartmentModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
using System.Collections.Generic;

namespace Ajax2.Models
{
    public class DepartmentsModel
    {
        public bool Filtered { get; set; }
        public IEnumerable<DepartmentModel> Departments { get; set; }

        public DepartmentsModel()
        {
            Departments = new List<DepartmentModel>();
        }
    }
}

DepartmentModel is the model that will be used for each line of the table. DepartmentsModel will be our view model for our page. In this view model we have a collection of all our departments to be displayed in our table and whether we apply some filtering.

Create or modify a view (I modified the Index of the Home controller) likewise:

@model Ajax2.Models.DepartmentsModel

@{
    ViewBag.Title = "Home Page";
}

<br />

@using (Ajax.BeginForm("FilterDepartmentsAjax",
                   new AjaxOptions
                   {
                       HttpMethod = "POST",
                       InsertionMode = InsertionMode.Replace,
                       UpdateTargetId = "department-table"
                   }))
{
    <label>Filter: </label>
    @Html.CheckBoxFor(model => model.Filtered)
    <input type="submit" value="Submit" />
}

<div id="department-table">
    @{ Html.RenderPartial("DepartmentsTablePartial", 
                          Model); }    
</div>

The first thing to note is we are using the AjaxHelper. Alternatively we could write JavaScript code ourselves, the AjaxHelper is just a convenience. When choosing to write the JavaScript code ourselves, we must use jQuery which is what the helper is using.

The important bits is that we want to replace an element identified by the id department-table.

When we call this form, the contents returned by the Ajax action on the controller will replace the contents of the div. We will replace the div’s content with a partial view, so we might as well reference it right now.

Note that it is possible not to render the partial view before making the first Ajax call which can make sense in some scenarios.

The partial view is nothing special:

@model Ajax2.Models.DepartmentsModel

<table class="table table-striped">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>

    <tbody>
        @foreach (var department in Model.Departments)
            {
            <tr>
                <td>@department.Id</td>
                <td>@department.Name</td>
            </tr>
        }
    </tbody>
</table>

Note that it contains the same model as it’s parent view. This is convenient in our scenario, but a different model could be used instead.

Now for the controller:

using Ajax2.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Ajax2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new DepartmentsModel
            {
                Filtered = true,
                Departments = GetDepartments(filtered: true),
            };

            return View(model);
        }

        [HttpPost]
        public PartialViewResult FilterDepartmentsAjax(DepartmentsModel model)
        {
            var updatedModel = new DepartmentsModel
            {
                Filtered = model.Filtered,
                Departments = GetDepartments(filtered: model.Filtered),
            };

            return PartialView("DepartmentsTablePartial", 
                               updatedModel);
        }

        private IEnumerable<DepartmentModel> GetDepartments(bool filtered)
        {
            var departments = new List<DepartmentModel>
            {
                new DepartmentModel { Id = 1, 
                                      Name = "Sales" },
                new DepartmentModel { Id = 2, 
                                      Name = "Accounting" },
                new DepartmentModel { Id = 3, 
                                      Name = "Marketing" },
                new DepartmentModel { Id = 4, 
                                      Name = "HR" },
                new DepartmentModel { Id = 5, 
                                      Name = "IT" },
                new DepartmentModel { Id = 6, 
                                      Name = "Customer S." },
            };

            if (filtered)
                return departments.Where(x => x.Id < 4);

            return departments;
        }
    }
}

GetDepartments is meant to be a placeholder. Normally in a real application we would get the data from a data source or a service.

Our FilterDepartmentsAjax must be decorated with the [HttpPost] attribute, return a PartialViewResult and use a return statement that returns a return PartialView rather than a view.

A UI improvement

Rather than have a submit button, it would be better to have the table update when the user check’s the filter checkbox.

Normally we could have just called this.form.submit() on the checkbox likewise

@Html.CheckBoxFor(model => model.Filtered, 
                  new { onclick = "this.form.submit();" })

but sadly this doesn’t work with Ajax. Courtesy of this stackoverflow answer we can submit it likewise:

@Html.CheckBoxFor(model => model.Filtered, 
                  new { 
                     onclick = "$(this).parents('form:first')
                                       .find(':submit')[0]
                                       .click();" 
                  })

And then hiding the existing input element (which must remain on the page).

Conclusion

I have posted the code on GitHub and you can find it here.