Steven Zack
Steven Zack

Reputation: 5104

how to add javascript to asp.net user control?

I found that even I use ResolveUrl to indicates the path, it still does not work unless I add javascript in the page that user control is embeded in.

<script src="<%= ResolveUrl("~/JS/jquery.js") %>" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function(){
       alert("aaaaa");
});
</script>

Is there a way to add JS into user control directly?

Upvotes: 1

Views: 3945

Answers (2)

Jason
Jason

Reputation: 52523

If you're talking about creating UserControl-specific javascript, I know exactly what you're talking about. There's no real easy way to do it (aside from just adding a script tag with your script and/or src), so here's what I do:

  1. Create your user control
  2. Create your js specific to that control in a separate .js file
  3. At the top of your user control, put a big flowerbox type comment that lists all the file dependencies for that control. This includes CSS (maybe you have your css separated out too) and any JS files.
  4. When you drop in a control, get in the habit of opening it up first and taking a look at your dependencies. This will ensure that you drop in the correct files too.

Also, naming your separate JS file the same thing as your User Control helps.

Upvotes: 1

Marc B
Marc B

Reputation: 360572

<input type="checkbox" onclick="alert('you clicked me!') />

is one tiny sample. Beyond that, we'd need details of what you mean by "control".

Upvotes: 0

Related Questions