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

后端 未结 5 1350
囚心锁ツ
囚心锁ツ 2020-12-19 07:45

As in question. Is it possible to set variable in asp.net page in localStorage and retrieve it on the other page?

How to set localStorage variable in asp.net. Is it

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 08:08

    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;
    }
    

提交回复
热议问题