Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get tempdata/ session/viewbag values in external javascript file

I have a custom AuthorizeAttribute defined in which when the user is unauthorized I am setting a tempdata["UnAuthorized"]=true. I am trying to access this value in an external javascript file which is referenced in the cshtml view, but I am uanble to get the value, it errs out Below is the custom authorize piece

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult("/");
        base.HandleUnauthorizedRequest(filterContext);

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //if not logged, it will work as normal Authorize and redirect to the Login
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Controller.TempData ["UnAuthorized"] = true;
            filterContext.Result = new RedirectResult("/Error");
        }
    }

This is how I am trying to access it in my external .js file

function SetData(data) {
        var test = TempData["UnAuthorized"];
        if (!test)
        {
            $('#SetModal').html(data);
            $('#SetModal').dialog('open');
        }

    }

I am unable to retrieve the value stored in TempData. Please suggest. I am using asp.net mvc 5, jquery, C#

like image 346
user3557236 Avatar asked Nov 17 '25 17:11

user3557236


1 Answers

Put another script in your razor view to store the value in a javascript variable and then you can use the value in your external file.

Razor:

@section scripts {
    <script type="text/javascript">
        var unauthorized = '@TempData["UnAuthorized"]';
    </script>
    <script type="text/javascript" src="~/Content/Scripts/external.js">
}

External.js

if(unauthorized) {
    alert("unauthorized");
}
like image 95
James Sampica Avatar answered Nov 20 '25 11:11

James Sampica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!