Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
aspx:

string name ="something";

i need to access this value in separate .js file
Posted

Try (in your script)
var mJSVariable = <%:myServerSideVariable%>;
 
Share this answer
 
Comments
Member 12119075 4-Jan-16 2:40am    
am not getting value, i tried with alert box am just getting out put like <%=myServerSideVariable%>
Follow below process to accomplish:

Step 1: Declare variable as public and static in code-behind file
C#
public partial class Page1 : System.Web.UI
{
   public string firstName = "Manas";
   
   protected void Page_Load()
   {
     // Your logic
   }
}

Step 2: Access the variable in js file:
JavaScript
<script>
    GetMyName();

    function GetMyName()
    {
	     alert(<%=this.firstName%>);
    }
</script>

Edit(Another way):
C#
public partial class Page1 : System.Web.UI
{
   public string firstName = "Manas";
   
   protected void Page_Load()
   {
     // Your logic
     string script = string.Format("var firstName = '{0}';", "Manas");
     if (!ClientScript.IsClientScriptBlockRegistered("myScript"))
     {
         ClientScript.RegisterClientScriptBlock(this.GetType(), "myScript", script, true);
     }
   }
}


Add code in temp.js file
JavaScript
<script>
    GetMyName();

    function GetMyName()
    {
	alert(firstName);
    }
</script>
 
Share this answer
 
v5
Comments
Member 12119075 4-Jan-16 3:01am    
its working fine if i give above the code in aspx file . am trying like this but not
getting

<script type="text/javascript" src="JScript1.js">

</script>


JScript1.js:

GetMyName();

function GetMyName()
{
alert(<%=this.firstName%>);
}
Member 12119075 4-Jan-16 4:15am    
can any one help me plz
[no name] 4-Jan-16 4:19am    
Please recheck my answer, it is edited.
Member 12119075 4-Jan-16 6:20am    
am not getting exact output , not showing any alert box
Member 12119075 6-Jan-16 2:41am    
I achived like bellow code , do u prefer to do like this i had suggest to do like this

localStorage.setItem('value', '<%=firstName%>');
var data = localStorage.getItem('value');
// `document.write(data);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900