MVC error handling with Json data

In like, 90% of cases, I do my form submits through ajax posts to the Controller:

$("form").on("submit", function () { if ($(this).valid()) { $.post($(this).attr("action"), $(this).serialize(), function (data) { if (!data.IsOK) { // something went wrong with the post so display a modal with error // detail here } else { // the post went through fine, reload the Index view window.location.href = '@Url.Content("~/User")'; } return; }); return false; } }); 

This just posts the view model to the controller so as to provide data with which to update the database, but now I've noticed something about the Index view – it doesn't expose itself to this type of error reporting.

For example:

With an Index view that just lists model data as per below:

@model IEnumerable<Ortund.Models.User> @if (Model != null && Model.Count () == 0) { <p>Viewing @Model.Count() registered Users</p> <table> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(x => item.Username)</td> </tr> } </table> } else { <p>No users exist. @Html.ActionLink("Create one.", "Create")</p> } 

If, for example, the controller queries a web service and the web service is down (based on a test case I set up), while the Controller will catch the error, it'll just go on and show the Create action link as if all that happened was that there was no records to display.

Here's my Index action in the controller:

public ActionResult Index() { try { } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine(String.Format("An error occurred: {0}", ex.Message)); return Json(new { Title = "LIST USERS", Message = HttpUtility.HtmlEncode(sb.ToString()), Error = ex.ToString(), // shown only to admin users - hidden by default IsOK = false }); } } 

Is there any way I can use an ajax GET to load the view data so as to put the check into this view? The idea is to get the same error reporting that applies to posts to work correctly on the GET requests too.

by ortund via /r/csharp

Leave a Reply