是否可以在asp.net页面中设置localStorage或Session变量,并在另一页的javascript中读取它?

mas*_*het 5 javascript c# asp.net session-variables local-storage

如有问题.是否可以在localStorage中的asp.net页面中设置变量并在另一页面上检索它?

如何在asp.net中设置localStorage变量.可能吗?之后我可以使用以下方法读取变量:

localStorage.getItem('UserID');
Run Code Online (Sandbox Code Playgroud)

Krz*_*lak 9

我想你不能.本地存储的全部意义在于它是本地的,你只能从javascript操作它.如果您需要在服务器和客户端之间传递值您需要使用一些传输技术 - cookie,ajax调用,隐藏字段等.这将取决于您的应用程序的组织方式,存储的信息类型,数量,是否你想要重定向或不重定向,但在所有情况下,这应该使用javascript完成,因为这是访问存储在localStorage中的数据的唯一方法.


Hou*_*and 8

旧帖子是的,但知识总是好的。

您可以从 asp.net(间接)设置本地或会话存储。由于我们可以在asp.net中设置javascript代码并插入到客户端,因此与会话或本地存储没有区别。

从服务器端试试这个

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

这会将会话(您可以执行本地)存储变量设置为值 12345。


mas*_*het 5

我已经通过使用 cookie 完成了此操作:

Default.aspx.cs背后的代码:

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

未设置 HttpCookie 过期。它默认随会话过期。

html 页面 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;
}
Run Code Online (Sandbox Code Playgroud)