hanssens / localstorage

LocalStorage for .NET - A simple and lightweight tool for persisting data in dotnet (core) apps.
MIT License
74 stars 17 forks source link

Using localstorage in .net web forms #27

Closed Harties closed 5 years ago

Harties commented 5 years ago

Hi, Firstly I would like to find out if it will work in asp.net web forms and seconds, I managed to get it working and saved a number of variables using the storage example but how would I retrieve the values from the store on a different page? rgs Zack

Harties commented 5 years ago

Briefly to scetch what I am trying to do: I have a capture form where I capture values from a user. After saving the values I then go to another page (eCommerce transaction on different domain) and the results from the eCommerce app opens a page within my domain and the same website that I called from. I would then, upon pageload, like to read the vales that I stored in the localstorage. I have previously tried this with cookies but too unstable. The code I am currently using to store the values below.

using Hanssens.Net; var storage = new LocalStorage(); string PFMemberName = ""; string value = Firstname.Value; storage.Store(PFMemberName, value); string PFMemberSurName = ""; string value1 = Surname.Value; storage.Store(PFMemberSurName, value1); string PFUsername = ""; string value2 = item3_text_1.Text; storage.Store(PFUsername, value1); string PFMemberEmail = ""; string value3 = item3_text_1.Text; storage.Store(PFMemberEmail, value3); string PFPWD = ""; string value4 = item3_text_1.Text; storage.Store(PFPWD, value4); I would now like to retrive these values on another page. Not sure how to do this.

hanssens commented 5 years ago

Seems like you're almost there @Harties. The basic usage what you did in your example is just fine. For example, storing a value:

    public partial class ExamplePage : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var container = new LocalStorage())
            {
                container.Store("PFMemberName", "somevalue");
            }
        }
    }

To read out the value, in any other page, simply use:

    public partial class AnyOtherPage : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var container = new LocalStorage())
            {
                if (container.Exists("PFMemberName"))
                {
                    myTextBox.Text = container.Get<string>("PFMemberName");
                }
            }
        }
    }

Notice in the second example, I did a null-check using .Exists() to see if the value actually exists.

As a tip, you'd might want to consider to to store all values as a class (model) rather than each property separately.

And to conclude, please be aware that with the way you set it up now it isn't suited for concurrent usage, e.g. multiple users. Each time your codesample runs the values are overwritten.