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

6

16

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 possible? After that I could read variable using:

localStorage.getItem('UserID');
Vagrom answered 24/10, 2013 at 9:20 Comment(1)
Local storage isn't ASP.NET, it's a web browser API. You use javascript to work with it. As to your Session question, you can always make a request to the server to get any value you might generally want, if you've built something to answer those requests. So... what's your question?Trouvaille
G
13

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.

Grotesque answered 24/10, 2013 at 9:37 Comment(3)
string myScriptValue = "function callMe() {alert('You pressed Me!'); }"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true); But i dont think mixing code behind and javascript is a good idea - just a sugestion. Anytime you need to make a simple change/update to your javascript you'll have to re-build your project, which means re-deploying instead of simply pushing out a single .js file.Grotesque
I've tried this way, but it needs Postback. In my case it isn't possible. Thanks for answers ;)Vagrom
you can output Javascript from ASP .Net so anything that can be done in Javascript can be done in ASP .NetAlaniz
G
9

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.

Gaona answered 9/5, 2018 at 17:11 Comment(0)
V
5

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;
}
Vagrom answered 24/10, 2013 at 10:36 Comment(0)
V
3

I think setting session variable in page & read variable in javascript of another page is possible. But, if you are looking out for localstorage that won't be. It needs javascript. For session variable e.g.
A.aspx

<% Session["username"]="Donald Duck"; %>

B.aspx

>  <script type="text/javascript">
>       var user = "<%= Session["username"] %>";
>       document.write(user);
>  </script>
Visakhapatnam answered 24/10, 2013 at 10:7 Comment(2)
The second page isn't .aspx page, but html + js only.Vagrom
Yes, it would be possible in html+js too.Visakhapatnam
L
2

A pure C# solution is currently available using Asp.Net Core and Blazor components with ProtectedBrowserStorage.

  • Add a blazor component to the project
  • Inject ProtectedLocalStorage or ProtectedSessionStorage into the component
  • Use GetAsync<T> and SetAsync<T> methods to store and retrive data from local storage. Any object type can be used with T.
  • Blazor components can be used inside Razor Pages and MVC projects as well.

Set Local Storage Component

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage LocalStorage

<button @onclick="async ()=> await SaveToLocalStorageAsync()">Save</button>

@code {
    private const string _localStorage = "MyLocalStorage";

    private async Task SaveToLocalStorageAsync()
    {
        await LocalStorage.SetAsync<string>(_localStorage, "text to be saved");
    }
}

Read Local Storage Component

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage LocalStorage

<p>@TxtFromLocalStorage</p>

@code {
    private string TxtFromLocalStorage = string.Empty;
    private const string _localStorage = "MyLocalStorage";

    protected override async Task OnInitializedAsync()
    {
        var result = await LocalStorage.GetAsync<string>(_localStorage);
        TxtFromLocalStorage = result.Success ? result.Value : "Can't read local storage";
    }
}
Limn answered 2/5, 2021 at 9:24 Comment(0)
F
1

you can use asp:HiddenField

after changed localstorage or sessionStorage you fill hidden field and use in code behind.

Furze answered 1/11, 2019 at 18:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.