ASP.NET MVC Authorize attribute to run modal?

I am working on a site that uses jquery modal dialogs to perform various actions such as logging in, etc.

Nevertheless; we have one small problem with using these ... that we use the [Authorize] attribute for many of our action methods, and therefore it happens that the user is not logged in and did not type the route that they need, so that the authorized one shows it The login page is supposed to be, but obviously it’s supposedly modal.

In short, is there a way to create a custom authorize attribute that can trigger the modal rather than the actual view that makes up the input mod?

+6
jquery model-view-controller asp.net-mvc modal-dialog
source share
1 answer

In this case, you can use the custom action filter attribute, which opens a pop-up window if the user is not logged in.
In this action filter, simply check if the user is registered and add a boolean to the ViewData collection.
Aplly attribute of an action controller.
Then, on the main page, add a conditional code rendering that opens a pop-up window.

Attribute Code:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class PopupAuthorizeAttribute : AuthorizeAttribute { private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) { validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); } public override void OnAuthorization(AuthorizationContext filterContext) { bool isAuthorized = false; if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (this.AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; cache.SetProxyMaxAge(new TimeSpan(0L)); cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null); isAuthorized = true; } filterContext.Controller.ViewData["OpenAuthorizationPopup"] = !isAuthorized; } } 

On the main page or other general view, add conditional rendering:

 <% if((bool)(ViewData["OpenAuthorizationPopup"] ?? true)) { %> ...Your code to open the popup here... <% } %> 
+5
source share

All Articles