vindh123
vindh123

Reputation: 144

MVC 3 Ajax error handling in jQuery

i have the following code that opens a dialogue with a View.

$('.bulkEditlink').click(function () {
    var f = $('td:first', $(this).parents('tr')).text();
    var r = tableCols().toString();
    loadBulkEdit(f, r); //loadBulkEdit is defined on RoleCompare View.
});

--load view with get

function loadBulkEdit(f,r) {
        var  $urlpath = "@Url.RouteUrl(new { area = "Admin", controller = "Role", action = "RoleEntitlementEdit"})";
        $.ajax({
            url: $urlpath,
            type: 'GET',
            data:  { 
                        funct: f, 
                        roleName: r, 
                        access: 'access' 
                    },
            OnFailure: "alert('error')",
            success: function (data) {
                $("#ajax-content").html(data);
                loadAccess();
            }
        });
} //end loadBulkEdit

--Dialogue box. On save, calls SaveRoleEntitlement action method (Ajax.BeginForm options defined on view

function loadAccess(xhr, status) {
        $('#ajax-content').dialog({
            modal: true,
            width: 370,
            title: $('#ajax-content legend').text(),
            buttons: {
                "Save": function () {
                    $('#ajax-content form').submit();
                   $(this).dialog('destroy').html('');
                },
                "Cancel": function () {
                    $(this).dialog('destroy').html('');
                }
            }
        });
    } //end popup

--Controller action

public JsonResult SaveRoleEntitlement(RoleEntitlementEidtModel model)
        {
            try
            {

                string strPackageName = model.RoleName;
                string strFebSecID = User.Identity.Name;
                string strKeyValue = "";
                string strFunction = model.Function;
                string strAccessLevel = model.AccessLevel;

                PatService.EditEntitlement(strFebSecID, strPackageName, strFunction, strAccessLevel, strKeyValue);
                return Json(new { Error = string.Empty });
            }
            catch (Exception ex)
            {
                return Json(new { Error = ex.Message });
            }
        }

This works fine except that I'm struggling to add 1. Error handling on Save. I want to show error message to the user if there are any exceptions 2. Progress bar or a sort of 'wait' message while the method executes. Hope someone will help me.

Thanks.

Upvotes: 0

Views: 2184

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

It would really depend on how/where you want to show the error message. The first possibility is to return JSON in case of an error (as you currently do) and then subscribe to the OnSuccess handler in your Ajax.BeginForm to handle this case:

@using (Ajax.BeginForm("SaveRoleEntitlement", "Role", new { area = "Admin" }, new AjaxOptions { OnSuccess = "saveRoleEntitlementSuccess" }))
{
    ...
}

and then define this success callback:

function saveRoleEntitlementSuccess(result) {
    if (result.Error && result.Error != '') {
        // there was an error => show it somehow
        alert(result.Error);
    } else {
        // the save was successful => do whatever you need to do in this case
    }
}

Another possibility if you want to handle validation errors directly on the UI is to return the same partial in case of an error:

public ActionResult SaveRoleEntitlement(RoleEntitlementEidtModel model)
{
    if (!ModelState.IsValid)
    {
        // there was a validation error => redisplay the partial form
        // so that fields appear in red
        return PartialView("RoleEntitlementEdit", model);
    }
    try
    {
        string strPackageName = model.RoleName;
        string strFebSecID = User.Identity.Name;
        string strKeyValue = "";
        string strFunction = model.Function;
        string strAccessLevel = model.AccessLevel;

        PatService.EditEntitlement(strFebSecID, strPackageName, strFunction, strAccessLevel, strKeyValue);
        return Json(new { success = true });
    }
    catch (Exception ex)
    {
        // we're gonna show this in a ValidationSummary
        ModelState.AddModelError("", ex.Message);
        return PartialView("RoleEntitlementEdit", model);
    }
}

and your Ajax form:

@using (Ajax.BeginForm("SaveRoleEntitlement", "Role", new { area = "Admin" }, new AjaxOptions { OnSuccess = "saveRoleEntitlementSuccess" }))
{
    @Html.ValidationSummary()
    ...
}

and your saveRoleEntitlementSuccess function this time:

function saveRoleEntitlementSuccess(result) {
    if (result.success) {
        // the save was successful => do whatever you need to do in this case
    } else {
        // there was an error => in this case the controller action returned
        // a partial that we could use to refresh the form in the DOM:
        $('#ajax-content').html(result);
    }
}

Upvotes: 1

Related Questions