Reputation: 815
I am new to C# and want to get my C# value in javascript
I found that by doing var javacriptVariable = "<%=CsVariable%>";
it should get the value CsVariable aut of my .cs file. However when I log it it logs <%=CsVariable%>
as a string
How can I get the value out m C# file?
Upvotes: 0
Views: 633
Reputation: 13
Upvotes: 0
Reputation: 8597
While Dans solution will work, here's an alternative that I'd personally go for..
Example usage:
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "script", string.Format("var myVariable = {0};", 123), true);
The following will render whatever you put inside the 3rd argument as a script on the page, therefore I'd put it in a PostBack or perhaps inside onPageLoad.
Upvotes: 0
Reputation: 564
The Approach I usually take is to assign the C# value to a hidden input field in which you can obtain the value data from javascript. In ASP.NET (Which it appears you are using, correct me if I am wrong) you can do something like
<asp:HiddenField runat="server" id="hdnCsVariable" />
And then in the backend .cs file on page load
hdnCsVariable.Value = "My C# Value";
And finally in the JS since ASP.NET will (usually) generate some hideous id, you can use the "ends with" selector to get your hidden input like so
console.log(document.querySelector("input[id$='hdnCsVariable']").value); // logs "My C# Value"
Upvotes: 1