Reputation: 13440
I'm trying to add some JQuery to an ASP.Net User Control to check to see if checkboxes have been selected or not. It appears that scripting languages are not supported directly in user controls, but need to be added via the RegisterStartupScript() method. I found a post at this url describing this: http://www.codeproject.com/KB/aspnet/Javascript_in_Usercontrol.aspx. The post says that in the code behind file you build up the syntax for the scripting code as a string and then send it as a parameter to RegisterStartupScript() method. I'm having problems getting this to work, and was hoping someone may know of a better way to add script to an ASP.Net User Control.
I've created a simplified sample and here is the markup for my user control:
<%@ Control Language="C#" ClassName="UC" AutoEventWireup="true"
CodeFile="UC.ascx.cs" Inherits="UserControls_UC" %>
<span id="Licenses"></span>
<script type="text/javascript">
$(document).ready(function() {
var ctlID = $("span[id$='Licenses']");
ctlID.text = "Testing";
});
</script>
If I include this script tag in the aspx file containing the user control, nothing happens. If I don't include it, I get a JavaScript error dialog saying there was a runtime error and that an Object was expected.
Upvotes: 1
Views: 6613
Reputation: 31
If you use the above approach without RegisterStartupScript()
, you will a face problem when you use the usercontrol multiple times in a same page.
So best suggested way is to generate script on the code-behind using RegisterStartupScript()
Upvotes: 3
Reputation: 1
The error you got is because the $
is not defined. You have to include the jQuery lib in the user control.
Upvotes: 0
Reputation: 4611
I think RegisterStartupScript() is the best solution for your task. Why don't it work for you? Is you use inline tag inside UserControl you have a chance to have a mess of Html & JavaScript blocks spaghetti, RegisterStartupScript() creates only one block.
Upvotes: -2
Reputation: 78262
All you need to do is drop a script tag on the control.
<script type="text/javascript">
$(function(){
if ($('input:checkbox:checked').size() === 5) {
// Do Something
}
});
</script>
Upvotes: 1