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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With