0

I have this code in my .aspx page:

$("#city, #<%=tbSiteSearch.ClientID%>").on('keydown', function (e) {

As you can see I'm dynamically injecting the clientid of a server side control.

Now when I move this codeline to an external .js file, I no longer have the availability of my ASP.NET tags.

How can I move my code to an external .js file while still being able to add the trigger on that server control dynamically? Please provide a code sample on how to do it :)

2
  • 1
    Which version of .NET? From version 4.5 you can assign a static ID to controls. And why not use a CSS class? Commented Jan 17, 2014 at 13:07
  • Use a CSS class, that will be much easier to do Commented Jan 17, 2014 at 13:08

3 Answers 3

2

An easy way is to include <%=tbSiteSearch.ClientID%> in your HTML (in a hidden container).

  <div id="myvalue" class="hidden"> <%=tbSiteSearch.ClientID%> </div>

Any js file can then use this value :

var id = $("#myvalue").text();
$("#city, #"+id).on('keydown', function (e) {
Sign up to request clarification or add additional context in comments.

1 Comment

And if I have 20 textboxes on the page then i will have to use 20 hidden fields ya?
1

You can use something like this in your ASPX:

<script>
     var tb=<%=tbSiteSearch.ClientID%>;
</script>

and then in your JS file use this:

$("#city, #"+tb).on('keydown', function (e) {

Comments

0

ASP.NET on IIS handles requests to some types of files. you can view this list by opening Internet Information Services (IIS) Manager, selecting your site and opening "Handler Mappings" you will see that ASP. NET (and others) listed against their respective file extensions. If you want to add javascript to be processed by ASP.NET you need to add a script mapping with the following values:

Request Path: *.js Executable: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll Name: Javascript ASP Handler

I really would not recommend this approach however as ASP.NET would be doing a lot more work for minimal benifit.

Your are much better off assigning an ID or Class to your element and selecting based on that.

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.