views:

154

answers:

2

Hi,

I have a little problem with a Jquery dialog for an action that requires a role. In my example, the user can click on a delete button and must confirm the action. In my controller, the Delete action requires a role, if the user is in the required role, the object is deleted.

The problem: How to alert the user if * the element was deleted (redirect to the Index view) * there was an error (alert with the message) * he doesn't have the rights to delete (alert with the message)

Before using the authorize filter, the delete action returned a JSON with a Boolean that indicates if there was an error, an URL to redirect on success and a message to alert on error.

As I can't return a JSON from my filter, I created an other method with the authorize filter that returns a partial view with the confirm content. If the user doesn't have the rights, the filter returns a partial view with an unauthorized exception content.

The problem: How to distinct which partial view was returned. When I create the dialog, I need to know for the buttons function.

Thanks!

A: 

I would suggest adding something to your Model where the jquery dialog is getting built like CanDeleteItem flag. Then build your dialog using that information instead of assuming they have the permissions to delete. Showing a button that the user can't use is a bad idea.

For other error situations, assuming you are using jquery.ajax to post to the delete action, the onerror event should be raised when an exception is thrown from the controller.

$.ajax({
  url: "/delete/5",
  type: "POST",
  success: function(json){
   // the delete happened
  },
  error: function(request, status, error){
  // it failed, authorization(403) or just an error (500)
  }
});
Jab
The problem is the redirection after an error 401. My ajax function never get an error but the content of my login view.
does your controller have the HandleError attribute? Try removing that attribute and see if the ajax function for the error then gets called.
Jab
A: 

Found a solution by adding code to the Global.asax:

protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 302 &&
            Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }