Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return PartialView with model from custom AuthorizeAttribute

At the core of what I'm doing, what I would like is if you go to www.mysite.com/admin/index I want to render a partial view that shows "Unauthorized" that has a Model attached to it. I was really not wanting the site to show www.mysite.com/error/unauthorized/ as that is not very useful when someone calls up and tells me I got an error on "/error/unauthorized" page, when I really want them to say "I got an unauthorized error on /admin/index page".

I have my CustomAuthorizeAttribute that inherits from AuthorizeAttribute working just fine, other than the redirect.

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    // returns boolean if it is good or not
}

Then I have my HandleUnauthorizedRequest and this is where I need to pass in a partial with a model:

if (context.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
    base.HandleUnauthorizedRequest(context);

}
else
{
    var viewResult = new PartialViewResult();
    viewResult.ViewName = "~/Views/Shared/Unauthorized.cshtml";
    viewResult.Model = new ViewModels.Unauthorized() { MyData = "My Data" }; // obviously can't do this as it is read-only

    context.Result = viewResult;
}

I know I can remove viewResult.Model and just use the ViewBag, but I was really hoping there was some way to pass in a model to the Partial

like image 745
Kyle Crabtree Avatar asked Oct 27 '15 19:10

Kyle Crabtree


1 Answers

Since PartialViewResult.Model is get only and returns ViewData.Model, all you have to do is to create and set the ViewData property:

var model = new ViewModels.Unauthorized() { MyData = "My Data" };
var viewResult = new PartialViewResult
{
    ViewName = "~/Views/Shared/Unauthorized.cshtml",
    ViewData = new ViewDataDictionary(model)
};
context.Result = viewResult;
like image 59
Daniel J.G. Avatar answered Sep 27 '22 22:09

Daniel J.G.