I have the following Ajax.BeginForm inside my asp.net MVC web application :-

@using (Ajax.BeginForm("AddZone", "DataCenter", 


    new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.InsertBefore,
    UpdateTargetId = "zonetableBody",
    LoadingElementId = "progress3",
    OnSuccess = "createsuccess",
    OnFailure="createfail"
}))
{

This will call the following action method:-

[HttpPost]
        [ValidateAntiForgeryToken]
        [CheckUserPermissions(Action = "Edit", Model = "Zone")]
        public ActionResult AddZone(DataCenterDetails z)
        {

I am performing a custom authorization action filter before executing the action methods, as follow:-

namespace TMS.Controllers
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class CheckUserPermissionsAttribute : ActionFilterAttribute
    {

        public string Model { get; set; }
        public string Action { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            int value = 0;
            Repository repository = new Repository();

            if (!repository.can(ADusername,Model,value))


                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {

                    var viewResult = new PartialViewResult();

                    viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
                    filterContext.Result = viewResult;

The problem I am facing is that if the user does not have the required permission to Edit , and he clicks on the ajax.beginform button he will receive the “/_Unauthorized.cshtml” view, but at the same time the Onsuccess script which display a message that the “Record was added successfully” will fire.

So my question is how I can prevent the Onsuccess script from being fired , in-case the _Unauthorized.cshtml is returned ?

Thanks

2

There are 2 best solutions below

6
On

You need to set the filterContext.Response.StatusCode. You can set it 500 or a code that does not mean OK;

0
On

I. AjaxOptions have OnComplete property which occurs before a call to either OnSuccess or OnFailure. To cancel the page update, return false from the JavaScript function.

see http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.oncomplete(v=vs.118).aspx

II. In case if you need global error handling for ajax request you should use .ajaxError()

$(document).ajaxError(function(event, request, settings) {
    if (XMLHttpRequest.status == 400) {
        window.location == "/Error";           
    }
});

Hope this helps