简体   繁体   中英

access local storge with javascript and C#, asp.net

i am hoping someone will help me, i am pulling out my hair for the last few hours...!

I am using asp.net web forms with c#

I have the following button in my menu , this button opens up a page that lists selected properties for realtor…

    htmlCode.Append("<button type='button' class='btn btn-basic' id='btnEnquire'   onclick='openEnquiryPage()'> <span class='glyphicon glyphicon-th-list'></span> View my list </button>");

     function openEnquiryPage() {
     location.href = "EnquiryPage.aspx";
    //get the list from the storage into the hidden field
    //getListOfProperties();//not in use...
    }

The list is stored in localstorage as Json, I can see the correct data in the text box on the page

   var retrievedData = localStorage.getItem("propertyArray");
   proplist2.value = retrievedData;

declared as follows in asp.net control

   <asp:TextBox ID="TextBox1" runat="server" Text="initial"></asp:TextBox>

BUT in the hidden field, the data is always = ""

  <asp:HiddenField ID="txtPropList" runat="server"></asp:HiddenField>

javascript to populate the hidden field...

    function getListOfProperties() {
    document.getElementById("body_content_txtPropList").value =    retrievedData;
   var proplist2 = document.getElementById("body_content_txtPropertyList");
    proplist2.value = retrievedData;
    }

when I debug the following lines in the code behind ...

    Page.ClientScript.RegisterStartupScript(this.GetType(),"prop", "getListOfProperties();",true);

    _propertyListJson = txtPropList.Value;

propertyListJson I always = “”

Thank-you in advance.!

If you want to use the hidden field then you should use <%=txtPropList.ClientID%> as on when you render the page and see it in inspect element server would render the different Id so it would not store the value in hidden field simply so it is feasible to use ClientID to create the static mode. But as on when you call the javascript function from the c# code then it would call the javascript function but it would not wait for it and execute the next line of code as on at that time the value is not store in hidden field so it would return the null value.

If you want then call the function of javascript on page load event and then click the button and retrieve the value it would successfully retrieve the value but i dont think that these would be the feasible code from my opinion

I suggest to create the WebAPI which would simply get the the data from the localstorage and perform the operation And webAPI can be easily called from javascript using ajax call

I hope this would be helpful and answer is satisfactory 😊☺

Thank You ☺🙂

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM