Tim567
Tim567

Reputation: 815

Get C# value in javascript

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

Answers (3)

Hassan Saleem Ullah
Hassan Saleem Ullah

Reputation: 13

  1. In Asp.net you can easily use
  2. Use Variable
  3. protected global::System.Web.UI.WebControls.TextBox MyTextBox;
  4. '<%= MyTextBox.ClientID %>'
  5. Use Function
  6. '<%=UI.ClassName.GetFunctionName%>'

Upvotes: 0

Adrian
Adrian

Reputation: 8597

While Dans solution will work, here's an alternative that I'd personally go for..

RegisterStartupScript

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

Dan Scott
Dan Scott

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

Related Questions