0

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
  • What exactly are you trying to do by making the src attribute dynamic? Commented Apr 29, 2010 at 1:11
  • I assume there's a server that's emitting different javascript depending on the URL parameters, and he doesn't know what they should be until runtime. Commented Apr 29, 2010 at 12:12

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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# :)

3 Comments

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 msdn.microsoft.com/en-us/library/… 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: I agree, of course, though I think you meant 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.
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.
2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.