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>
.
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.
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 + "'");
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.
精彩评论