Tuesday, March 19, 2013

JQuery in ASP.Net User Control in C#

http://stackoverflow.com/questions/1433972/jquery-in-asp-net-user-control-in-c-sharp


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.
share|improve this question
1 
Not sure that's 100% correct. What happens when you add the script directly to the html (design) view? – mxmissile Sep 16 '09 at 16:15
90% of the time is the function not right in my code if nothing happened – sam Mar 2 '10 at 22:42

4 Answers

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>
share|improve this answer

No comments:

Post a Comment