I need to access the session value in external js file. I have tried,
var userid = '@HttpContext.Current.Session["UserID"]';
this dosen't work as the variable userid take the right hand side as a string. Can anyone suggest me a idea.
You can access the Session
variable in .cshtml
and pass it to external javascript file by calling function of external .js
file.
var userid = '@Session["UserID"]';
externalJsFunction(userid);
You can assign session to some hidden field and get the hidden field value (session value) in document.ready in external js file.
I have one solution for you. In layout of your website define any empty div and set its data attribute value with session value if you are using html5 as,
<div id="sessionDiv" data-id="@Session["UserID"]"></div>
Now in your external js file access this div.
var userid=$('#sessionDiv').attr('data-id');
You could add a script
tag at the top of the .cshtml
file and assign a the userid
to a global variable. This variable is then accessible in all javascript files.
index.cshtml
...
<script>
document.mynamespace = {};
document.mynamespace.userid = '@HttpContext.Current.Session["UserID"]';
</script>
....
javascript.js
var userid = document.mynamespace.userid; //do something with userid
mynamespace is a proxy object so that you dont pollute the global namespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.