开发者

passing data to javascript on page load

开发者 https://www.devze.com 2022-12-29 01:40 出处:网络
I want to pass data to id <script language=\"javascript\" src=\"/foo.aspx?id=1\"></script>

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, b开发者_开发百科efore this code is being executed.

how can i do that?


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>


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


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>

0

精彩评论

暂无评论...
验证码 换一张
取 消