0

I have a string in my C# code-behind file in ASP.NET:

string data = "Data that is populated"; 
//Note: A method populates the actual data

I need to be able to convert this string to a JavaScript var. I know that using a Razor file is a common way to go and there are several questions on this topic, but I am unsure how to do this with a code-behind file, nor have I full understood the previous questions and answers.

4
  • What exactly is a code behind file? A .aspx.cs file? If so, why don't you do it from the .aspx file directly? Commented Sep 11, 2018 at 23:38
  • Do you need to send it to the browser? Commented Sep 11, 2018 at 23:38
  • @CamiloTerevinto yes, that what a code-behind file is, what exactly do you mean by directly with a aspx file? Commented Sep 11, 2018 at 23:55
  • @PoulBak I need to pass it in as a parameter for a JavaScript function Commented Sep 11, 2018 at 23:55

2 Answers 2

2

In a case like this, I set a HiddenField.Value to the string's value, like this, in aspx:

<asp:HiddenField ID="HiddenField1" runat="server" />

and then in code behind:

HiddenField1.Value = "some string";

Now in JavaScript you can read that value and pass it to your function:

var myValue = document.getElementById('HiddenField1').value;
myFuction(myValue);
Sign up to request clarification or add additional context in comments.

Comments

1

Use this code

protected void Page_Load(object sender, EventArgs e)
{
    string scriptCode = @"
        <script>
        let text = {0}; 
        alert(text);
        </script>";

    string message = "Hello World!";
    scriptCode = string.Format(scriptCode, HttpUtility.JavaScriptStringEncode(message, true));

    RegisterStartupScript("AlertCode", scriptCode);
}

The function RegisterStartupScript embeds JavaSript code into the page. Use JavaScriptStringEncode() to convert a string into a JavaScript string representation to use in that JavaScript code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.