views:

76

answers:

3

I want to pass data to id

<script language="javascript" src="/foo.aspx?id=1"></script>

I have this code in a aspx page.

The data should be passed on load, before this code is being executed.

how can i do that?

+2  A: 

Just have a property in your code-behind file, like

protected string FooId
{
    get { return ... }
}

Then in the ASPX file, reference it like this:

<script language="javascript" src="/foo.aspx?id=<%= FooId %>"></script>
Evgeny
+2  A: 

ASP.NET has a syntax <%= %> which is equivalent to Response.Write.

You can then store your id in a property, e.g.: protected int Id {get;set;} and set it in Page_Load

then, you'll do this:

<script language="javascript" src="/foo.aspx?id=<%= Id %>"></script>

Jim Schubert
+2  A: 

I've gotten more and more averse to putting <% %> in the .aspx file, mostly because you can get into terrible knots trying to escape various kinds of quotes.

Here's another way of doing it:

<asp:Literal id="myscript" runat="server"/>

Then on the server side, when you're handling Page_Load():

int theID = 42;
myscript.Text = string.Format("<script type=\"text/javascript\" " +
           " src=\"/foo.aspx?id={0})\"></script>", theID);

Edit: rewritten in C# :)

egrunin
i like this....
This is a good workaround, and I've used it for databound controls where a link's click function is dependent on its id. The better way to handle injecting the whole javascript is done with `Page.ClientScript.RegisterClientScriptBlock` http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx However, if you need to make code changes in the future to your javascript, you have to recompile your whole codebase, as opposed to making changes in the web form and moving around the `<%= %>` tag.
Jim Schubert
@Jim Schubert: I agree, of course, though I think you meant http://msdn.microsoft.com/en-us/library/btf44dc9.aspx . On the other hand, sometimes you need to control where exactly on the page the script is placed.
egrunin
@egrunin: yes your link points to the ClientScript.* version. I actually prefer this version because there is an overload for automatically including script tags, so you only supply the javascript. Adding the script tags is usually what gets me with the mismatched quotes.
Jim Schubert