开发者

In ASP.NET, is it possible to use the '<%= control.ClientID %>' in an external javascript file or must it be in the ASPX itself as script block?

In ASP.NET, is it possible to use the

'<%= control.ClientID %>' 

in an external javascript file or must it be in the ASPX itself as script block?

If it is not possible, are ther开发者_Go百科e any tricks to make this work?


Or you could register your client id's in an array and use this array in your javascript file.

Aspx(Js)

var pageControls = {
   'myControlId1' : '<%= control1.ClientID %>',
   'myControlId2' : '<%= control2.ClientID %>',
   ...
}

Javascript

alert(pageControls['myControlId2']);


As far as I know, it has to be in the aspx itself. What I have always done is pass it as an argument. Eg.

function doSometing(clientId){
...
}

from asp.net within a script block:

doSomething(<%= control.ClientID %>);


You can also simply register the page as an aspx page, such as renaming your file to MyFile.js.aspx

Then just add the <% Page %> directive at the top, and you can embed the ids as you mentioned.

However, this means the JS won't be cached by the browser (unless you specifically add caching yourself), and there's extra overhead because of the parsing required on the server.


In short, any code within server tags must go through the ASP.NET processing pipeline so that it can be written to the output. After all, <%= ... %> is just shorthand for Response.Write(...).

So, if you could get an external script file to go through the processing pipeline, then you could have server tags in it. An easier approach however is to write a server side control that emits a block of JavaScript into the page that contains the client side ids and a function that can be used that when passed the server side id, returns the client side id. Then use this function in your external scripts. Of course, in ASP.NET 4 (or MVC), you have better control over the IDs generated for the client side so can avoid this altogether.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜