Reputation: 61
I have a aspx page with a placeholder in an update panel. The user control is attached to the placeholder depending the value of a dropdown on the page. The user control loads correctly, but it seems that the click event of the button is not firing. I've put a breakpoint in the .js file, but it never goes into the js function. Not sure if the javascript is even loaded.
The aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page.aspx.cs" Inherits="UserControlTest.Page" %>
<%@ Register Src="~/TestUserControl.ascx" TagPrefix="uc1" TagName="TestUserControl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/testUserControl.js"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
<div>
<h4>This is the page</h4>
<div class="form-group">
<label class="col-md-5 control-label" for="selUserControl">Enquiry Type <span class="glyphicon glyphicon-asterisk pull-right" style="color:red"></span> </label>
<div class="col-md-7">
<asp:DropDownList ID="selUserControl" CssClass="form-control reqrd" runat="server" OnSelectedIndexChanged="selUserControl_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
</div>
</div>
<div id="divUserControl">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="phUserControl" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="selUserControl" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</form>
</body>
</html>
The aspx.cs page:
protected void selUserControl_SelectedIndexChanged(object sender, EventArgs e)
{
TestUserControl uc = (TestUserControl)LoadControl("~/TestUserControl.ascx");
uc.ID = "ucUserControl";
phUserControl.Controls.Add(uc);
}
The .ascx page:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="UserControlTest.TestUserControl" %>
<div>
<h4>This is the User Control</h4>
</div>
<div class="form-group">
<div class="col-md-7">
<input type="button" id="btnPress" class="btn" value="Press!" />
</div>
</div>
The .js file:
$(document).ready(function () {
$("#btnPress").click(function () {
alert('Hi There from User Control');
});
});
Upvotes: 0
Views: 1134
Reputation: 77378
By the time your js
is run, #btnPress
doesn't exist on the page (or at least the original #btnPress
doesn't. @DelightedD0D is right. I'd look into using event delegates and attaching them to your document. This way you can attach/detach as many #btnPress
as you'd like and your clicks will bubble to document and be handled by the delegate.
$(document).on('click', '#btnPress', function(){
alert('Hi There from User Control');
});
Upvotes: 1