1

I have some code that looks something like this:

<head runat="server">
  <script type="text/javascript">
     var params = {};
     params.param1 = 'value1';
     params.param2 = 'value2';
     params.param3 = 'value3';
     params.param4 = ''; // ASP.NET value 1
     params.param5 = ''; // ASP.NET value 2
     function.call(params);
  </script>
</head>

How do I use ASP.NET to populate param4 and param5? I've read about master pages and content placeholders, but is there a way that I can just do something like params.param4 = '<%= var1 %>'; or params.param4 = '<asp:var />';?

Edit

Thanks to everyone who answered so quickly. I must have had a parsing error or something that made me think this wasn't possible. Just to make it clear what I did to solve my problem:

ASPX page:

<head>
  <script type="text/javascript">
     var params = {};
     params.param1 = 'value1';
     params.param2 = 'value2';
     params.param3 = 'value3';
     params.param4 = '<%= var1 %>';
     params.param5 = '<%= var2 %>';
     function.call(params);
  </script>
</head>

CS Code-Behind:

public string var1 { get; set; }

public string var2 { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
   // setup code goes here
   var1 = 'param4';
   var2 = 'param5';
}

Note: You don't need runat="server" in the head, and just as long as the variables are public in the code-behind, they can be accessed via <%= %> in the <head>.

Community
  • 1
  • 1
JR.
  • 5,840
  • 9
  • 31
  • 34

3 Answers3

2

You sort of answered your own question. You can declare your variables in the code-behind and then use them in your code with <%= %> tags, or you can use the RegisterClientScriptBlock method to add the JavaScript to your page on the fly.

Scott Arrington
  • 12,325
  • 3
  • 42
  • 54
  • Heh, thanks. For some reason, I tried this yesterday but got errors when trying to use those tags. Not sure what I did differently this time, but whatever; it works now. ^_^ – JR. Jan 19 '10 at 17:35
1

you could do exactly that if weren't runat="server"

alternatively you could render out that params array server-side

Page.ClientScript.RegisterArrayDeclaration("params", "'value1','value2','value3','" + value4 + "','" + value5 + "'");
hunter
  • 62,308
  • 19
  • 113
  • 113
1

If your your values are public variables declared in the .cs part of the class you can do exactly what you described and read them out in server tags.

Sheff
  • 3,474
  • 3
  • 33
  • 35