简体   繁体   中英

How to call javascript function for local storage from C# code behind

I have javascript file to store user data in local storage. For some reason I need to call javascript code from C# code behind or from html page of site.

Here is my javascript code:

   LocalStorage.setItem("TestUser", JSON.stringify(
     {
       "Usr_UserAvatar": “Avartar”,
       "Usr_Username": “The username (string)”,
       "Usr_Email": “Email (string)”,
       "Usr_FirstName": “First name (string)”,
       "Usr_LastName": “Last name (string)”,
       "Usr_CompanyName": “Company name (string)”,
       "Usr_CountryCode": “Country code (string)”,
       "isAdmin": “If the user has admin rights (boolean)” 
     }
   });

How can I call this code form C# code behind? Please guide me how to do this.Thanks.

First, your question has nothing to do with LocalStorage . You just want to run some JavaScript code from ASP.NET.

Consider you are using WebForms, which I suppose because you used the expression Code behind , you could just do what @Angus said. Register a function in a client .js file and run it using RegisterStartupScript .

Alternatively, you could simply put this somewhere in your ASPX file, Masterpage or RazorView :

<script type="application/javascript">
   LocalStorage.setItem("TestUser", JSON.stringify(
     {
       "Usr_UserAvatar": “Avartar”,
       "Usr_Username": “The username (string)”,
       "Usr_Email": “Email (string)”,
       "Usr_FirstName": “First name (string)”,
       "Usr_LastName": “Last name (string)”,
       "Usr_CompanyName": “Company name (string)”,
       "Usr_CountryCode": “Country code (string)”,
       "isAdmin": “If the user has admin rights (boolean)” 
     }
   });
</script>

You can use ClientScriptManager to call your javascript function from C# code behind.

Page.ClientScript.RegisterStartupScript(
    Page.GetType(), 
    "test", 
    "FunctionName();", 
    true);

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