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?
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"
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.
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.