Is it possible to set localStorage or Session variable in asp.net page and read it in javascript on the other page?

I guess You can't. The whole point of local storage is that it is local and You can manipulate it only from javascript. If You need to pass values between server and client You need to use some transport technology - cookies, ajax calls, hidden fields etc. It will all depend on how your application is organized, what kind of information is being stored, its volume, whether you want to redirect or not, but in all cases this should be done using javascript since that's the only way to access data stored in localStorage.


Old post yes, but knowledge is always good.

You can set the local or session storage from asp.net (indirectly). Since we can set up javascript code in asp.net and insert into the client side, there's no difference with the session or local storage.

Try this from server side

string script = string.Format("sessionStorage.userId= '{0}';", "12345");
ClientScript.RegisterClientScriptBlock(this.GetType(), "key", script, true);

That will set the session (you could do local) storage variable to the value 12345.


I've done this by using cookies:

Default.aspx.cs code behind:

HttpCookie userIdCookie = new HttpCookie("UserID");
userIdCookie.Value = id.ToString();
Response.Cookies.Add(userIdCookie);
Response.Redirect("~/ImagePage.html");

HttpCookie Expires wasn't setted. It expires default with session.

html page javascript:

function OnLoad() {
var userId = getCookie('UserdID');
if (userId == null)
    window.location = "http://localhost:53566/Default.aspx";        
}

function getCookie(cookieName) {
    var cookieValue = document.cookie;
    var cookieStart = cookieValue.indexOf(" " + cookieName + "=");
    if (cookieStart == -1) {
        cookieStart = cookieValue.indexOf("=");
    }
    if (cookieStart == -1) {
        cookieValue = null;
    }
    else {
        cookieStart = cookieValue.indexOf("=", cookieStart) + 1;
        var cookieEnd = cookieValue.indexOf(";", cookieStart);
        if (cookieEnd == -1) {
            cookieEnd = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStart, cookieEnd));
    }
    return cookieValue;
}