views:

541

answers:

2

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%5Fin%5FUsercontrol.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.

+1  A: 

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>
ChaosPandion
A: 

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.

Roman
I have never had any problems with script tags in my controls.
ChaosPandion