<asp:Button> event not firing when within element affected by jQuery - javascript

I am creating an ASP.NET with C# calendar application. When a user clicks on a day, I am using a jQuery Popup Overlay which will allow the user to add an 'appointment' and click a button to process the entered information in the codebehind.
The Popup overlay basically hides an HTML element and makes it visible when another element is clicked (great examples by following link above).
The Code:
<asp:Button ID="ButtonA" runat="server" OnClick="Button_Click" Text="Button A" />
<asp:Label ID="Label" runat="server" Text="Foo"></asp:Label>
<div id='slide'>
<div id="content">
Content of the 'popup panel'
<asp:Button ID="ButtonB" runat="server" OnClick="Button_Click" Text="Button B" />
</div>
</div>
CodeBehind:
public void Button_Click(Object sender, EventArgs e)
{
Label.Text = "Bar";
}
Javascript:
$(document).ready(function () {
$('#slide').popup({
//options
});
});
I tried adding the AutoPostBack="true" parameter to the buttons, but it doesn't make a difference (should be automatic regardless, correct?). I also tried adding the runat="server" parameter to the div elements, but that made the issue worse.
I am afraid that I don't understand the nature of the issue enough to provide more information than this - Sorry!

It's likely that the jQuery plugin is overriding the behaviour of the button. You could use the onclose callback from the URL you provided to have a function like so:
function() {
__doPostBack("ctl00$MainContent$ButtonB","");
}
Failing that, you could have another button outside the popup div which you do a click() event on manually during the onclose event of the popup, but that seems like a bit of a hack!

Related

ASP/C# - UpdatePanel and Button OnClick Event Not Triggered

I've been trying to find the solution but it would be great if someone can take a look.
In my aspx page and C# codebehind I have the following:
aspx:
<asp:UpdatePanel runat="server" ID="UpdatePanel8" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddTableRow" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="divDynamicFields" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
<div hidden>
<asp:Button ID="btnAddTableRow" runat="server" OnClick="AddTableRow" />
</div>
<script type="text/javascript">
function addTableRow(tableId) {
$('#<%=btnAddTableRow.ClientID%>').click();
}
</script>
C#:
protected void AddTableRow(object sender, EventArgs e)
{
(...)
}
The event is triggered if I don't use UpdatePanel, but when executed with UpdatePanel, there is PostBack but the C# method is not called. I've tried to understand it for some time with no avail. Any ideas? Thank you.
After a good night sleep and a fresh mind, I finally found out what is failing. The JS function addTableRow(tableId) is actually called by buttons that are dynamically created in Page_Load (the number of these buttons are not fixed, hence associating them with this JS function which clicks the hidden button that triggers the event method from codebehind). Problem is, I was generating these buttons in the following way:
Button addRowButton = new Button();
addRowButton.Text = "This is my dynamically generated button";
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "')");
But things started working when I've changed to:
HtmlGenericControl addRowButton = new HtmlGenericControl("input");
addRowButton.Attributes.Add("type", "button");
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "');");
addRowButton.Attributes.Add("value", "This is my dynamically generated button");
It's actually kind of strange, since the button created with Button() still invoked JS function addTableRows and caused PostBack but didn't invoke the code behind method. Perhaps it had to do with the page life cycle and the generated IDs for the dynamic buttons that are generated in different ways depending on creating them as Button or HtmlGenericControl, but in any ways it's working now.

Data from entity framework displayed in javascript/Jquery dialog

I have a problem, and looking for a solution for 2 days
Target : Create/edit client... in HTML build a dialog with and asp fields with clientIDMode static
<div id="divDialog" runat="server" clientidmode="Static" style="display: none;">
<div class="DialogFields">
<asp:Label ID="Label1" runat="server" Text="Firstname"></asp:Label>
<br />
<asp:TextBox ID="tbxFirstName" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>
...
In script
$("#btnShowDialog").click(function () {
openDialog();
});
function openDialog() {
$("#divDialog").dialog('open');
$("#divDialog").parent().appendTo($("form:first"));
}
When I click the button btnShowDialog it works fine... But
Beneath it I have a gridview within it a edit button (asp:Linkbutton) with a event to the codebehind it looks like:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" OnCommand="Edit_Click" CommandArgument='<%#Eval("RelationID") %>'
runat="server"><img src="../images/Edit-item.png" alt="Edit" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
In codebehind take the parameter from commandargument and fire LoadInfo (specific data to all the fields in de dialog).
LoadInfo(e.CommandArgument != null ? int.Parse(e.CommandArgument.ToString()) : -1);
but no way I get the dialog open.
I tried
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "openDialog();", true);
and
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "openDialog();", true);
after this LoadInfo, push btnShowDialog button and it opens the dialog and all data perfect in place.
Also tried the other way around as Directly to Jquery function, get all data loaded and open the dialog. 2 problems, loading in codebehind was not even started before the dialog opens. and I only can get a static function in the codebehind.
A lot of ground to cover for me, but can any body help me out (even for a part).
...Thanx
If I understand your question correctly, you are trying to fire some client scripts (openDialog) from the server side, but they wont fire?
Try placing your page in an update panel, lets assume that we name the update panel "MyUpdatePanel". And then refer to the update panel like this:
ScriptManager.RegisterStartupScript(MyUpdatePanel, MyUpdatePanel.GetType(), "MyUpdatePanelScript", "openDialog();", true);

Unable to make ASP.NET control button fade out with JQuery

I have a simple enough problem: I have an ASP.NET control button and I want to make it fade out and then call some function (such as an alert) using JQuery. Here is what I have so far:
ASP Code for the Button:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
JavaScript:
function startButtonClick()
{
$("#startButtonSpan > input").fadeOut(500, callAlert());
}
function callAlert()
{
alert("Made it here...");
}
When I click the button, the alert displays but the page does not even seem to try to perform the fadeOut. When I close the alert, the button is still there, staring at me.
Can anyone see any mistakes or does anyone have any suggestions on how I might be able to achieve the intended goal of fading out my button? Fadeout is really just my way of testing whether I can manipulate ASP controls using jQuery, so more than just the simple fadeOut, this is me trying to learn how to do that.
I tried a slightly more simple jQuery call using the code below, but it does not seem to work either:
ASP Portion:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
<div id="jQueryTest" style="display:none;">
Block for testing jQuery.
<h1 id="testMessage">Child element for the ASP div.</h1>
</div>
Javascript Portion:
function startButtonClick()
{
$("#jQueryTest").css("display", "block");
$("#jQueryTest").show();
}
For this example, the text does display, but it immediately disappears again.
Any help or suggestions as to what I might be doing wrong would be greatly appreciated.
Use the class as a selector $('.startButton') instead of the ID since ASP.Net controls change their IDs dynamically when rendered by appending its Page & Control information.
$(".startButton").fadeOut(500, callAlert);
Or, if you're adamant about using the ID, here is another way to handling the selector,
$("#<%=startButton.ClientID %>")
Or, as Jacob suggested in his answer, you could ClientIDMode="Static", but this works only if your application is .Net 4.0 or above.
Also, use CssClass instead of class
<asp:Button ID="startButton" Csslass="startButton" runat="server" Text="Click Me!" />
The first example has 2 problems.
1. You should write
$("#startButton").fadeOut(500, callAlert);
and not
$("#startButton").fadeOut(500, callAlert());
2. For ASP.NET you must set ClientIDMode="Static" ortherwise asp.net will alter your id.
<asp:Button ID="startButton" ClientIDMode="Static" ... OnClientClick="startButtonClick()"/>
How about the fact that your code is fine (although other answers here should be considered) but your button is making a post back to the server and simply your browser does not have enough time to render the fade effect.
To test this, add a return false; to the OnClientClick property. This will of course cancel your action on the server but you will obtain the fade effect:
<asp: Button ... OnClientClick="startButtonClick();return false;"></asp:Button>
To work around this and still submit your request, you can try to use the ASP.NET __doPostBack method in JavaScript
ASP.NET:
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick(this);return false;"/>
JavaScript:
function startButtonClick(button)
{
$("#startButtonSpan > input").fadeOut(500, function(){__doPostBack(button.name, "")});
}
The __doPostBack method takes two arguments: the name of the control that is doing the postback and a postback argument that can be use to send more info on the server. In the case of the asp:Button, the name of the button should be sufficient to send the request without a problem.
Using this technique you will fade the button on the client and also trigger the action on the server. I cannot guarantee that this exact code will work (I don't have access to a dev environment right now) but you should get the idea.
If I could, I would like to provide another answer for those that use MasterPages and find that you can't always use $("#<%= SomeContentControl.ClientID %>") when working with Content controls.
What I do is set the MasterPage ID in my Init() like this:
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}
Then, you can do something like this with your jQuery:
var masterId = "Mstr",
$startButton = getContentControl("startButton"),
$message = $("#jQueryTest");
function getContentControl( ctrlId )
{
return $("#" + masterId + "_" + ctrlId);
}
function hideStartButton()
{
$startButton
.stop(true, true)
.fadeOut("slow", showMessage);
}
function showMessage()
{
$message
.stop(true, true)
.fadeIn("slow");
}
$startButton.on("click", hideStartButton);
Here is a jsFiddle that has the Mstr_ prefix already inserted as if ASP.NET rendered it.

asp:Button in jQuery dialog box not firing OnClick event

I have an asp:Button inside a jQuery dialog for which the OnClick event isn't firing. I'm using the PostBackUrl property to navigate to another page, but I want to set this property in the OnClick event so that I can append a query string variable according to the name of a file they upload in the dialog. I posted a question about this dialog earlier, because I couldn't get it to post back at all, but that's been fixed. Clicking the button posts back fine, and I can set the PostBackUrl property in the asp markup, or in the Page_Load() of the code behind. But I can't get the OnClick function to fire for some reason, and that's where I want to set the PostBackUrl. Here's the .aspx...
<form id="frmDialog" runat="server">
<asp:Button ID="btnDisplayDialog" runat="server" Text="Click to Display Login Dialog" OnClientClick="showDialog(); return false;" />
<div class="divInnerForm"></div>
<div class="divDialog" style="display: none">
<table style="width: 100%;">
<tr>
<td>First Name: <asp:TextBox ID="txtFirstName" runat="server" Text=""></asp:TextBox></td>
<td>Last Name: <asp:TextBox ID="txtLastName" runat="server" Text=""></asp:TextBox></td>
</tr>
<tr>
<td>
How Old are You?
<asp:DropDownList ID="ddlAge" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>
</td>
<td>
How Many Siblings do You Have?
<asp:DropDownList ID="ddlNumberSiblings" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
What is your birthday?
<input type="text" id="datepicker" name="datepicker" />
</td>
</tr>
<tr>
<td>
Please Choose a Picture to Upload:
<asp:FileUpload ID="fupUserPicture" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnUserPicture_Click" />
</td>
</tr>
</table>
</div>
</form>
...the jQuery script that displays the dialog and places it within the form...
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500,
open: function (event, ui) {
$('.divInnerForm').append($(this).parent());
}
});
}
...and the code behind with my OnClick function....
protected void btnUserPicture_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
btnSubmit.PostBackUrl = "~/Profile.aspx?pic=" + fileName;
}
}
EDIT: Ok, here's how the submit button in the dialog actually renders as HTML. I think this may be the problem. As you can see, the javascript onclick simply provides "Profile.aspx" as the post back url, even though it seems to me any server side code should execute first and foremost. This is within the form...
<input id="btnSubmit" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSubmit", "", false, "", "Profile.aspx", false, false))" value="Submit" name="btnSubmit">
..and here's how it renderes if I remove btnSubmit.PostBackUrl = "~/Profile.aspx" from the Page_Load() function....
<input id="btnSubmit" type="submit" value="Submit" name="btnSubmit">
EDIT 2: ok so I've added another hidden asp button outside of the dialog, and the button inside the dialog now calls a javascript function which triggers the OnClick event of the hidden button. Same thing, the javascript function runs fine, but btnHidden_Click() function does not run! I'm at a total loss, at this point I literally have no idea why this isn't working. Here's the new Hidden Button, outside of the dialog div but inside of the form as you can see....
</div>
<asp:Button ID="btnHidden" runat="server" Text="" Visible="false" ClientIDMode="Predictable" OnClick="btnHidden_Click"/>
</form>
...here's the button inside the dialog with the OnClientClick event, which as I've said runs fine...
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forcebtnHiddenClick(); return false;" />
And here's the OnClick function in the code behind for btnHidden, though it's exactly the same as before...
protected void btnHidden_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
Response.Redirect("~/Profile.aspx?pic=" + fileName);
}
}
...and the javascript function that runs, but for some reason doesn't result in btnHidden_Click running...
function forcebtnHiddenClick(e) {
//__doPostBack('btnHidden', 'OnClick');
$('#btnHidden').trigger('click');
}
..as you can see I've tried both .trigger('click') and __doPostBack(), both to no avail.
EDIT: Ok, so the problem is definitely the
function forcebtnHiddenClick() {
__doPostBack('btnHidden', '');
}
function, which is not actually triggering the btnHidden_Click event. When I make btnHidden visible and click it directly, the btnHidden_Click function runs fine.
EDIT: After TONS of searching, found this and got it to work...
function forcebtnHiddenClick() {
<%= ClientScript.GetPostBackEventReference(btnHidden, string.Empty) %>;
}
I don't know why
__doPostBack(<%= btnHidden.ClientID %>, '')
doesn't work.
Try this
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500
});
$(".divDialog").parent().appendTo($("form:first"));
}
You should be appending divDialog to the form not that empty divInnerForm.Then your button will be in the form and its on click event will fire happily.
Update
Try also using onclient click.Then wire this attribute to a function which will force a post back on the hidden button.
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forceClick();" />
<asp Button id="hidButton" runat="server" onclick="hidButton_Click" />
function forceClick(){
__doPostBack('<%#hidButton.UniqueId %>');
}
Then use the event handler hidButton_Click to put your code.
$(this).parent().appendTo('form')
should work fine.. Append it to the form to fire server side events
When I use the jQuery dialog, I always use the buttons that come as part of the dialog. Then when they're clicked, I call a javascript function to perform my action.
If I need to handle a PostBack from those buttons, then I create a separate ASP.Net button on the page - this is the button I use to handle my OnClick event. The user won't click this ASP.Net button, though (I hide it with css so it's not visible on the page). Instead, the javascript function I call when they click the dialog button will call code that will mimic a click of my ASP.Net button.
The result is that when the dialog button is clicked, the page will PostBack as though the ASP.Net button was clicked, and I can handle it via my OnClick event.
Here's some sample code (in VB.Net)...
Dim csm As ClientScriptManager = Page.ClientScript
Dim js As New StringBuilder
js.AppendLine("function handleSubmitMyButton() {")
js.AppendLine(csm.GetPostBackEventReference(MyButton, ""))
js.AppendLine("}")
csm.RegisterClientScriptBlock(Me.Page.GetType, "create_call_to_MyButton", js.ToString, True)
When the page is built, it will include the handleSubmitMyButton() javascript function. The dialog button click will call this function, which will trigger the PostBack as though the 'MyButton' button was clicked.
Usually I don't have to hide the ASP.Net button with css. It's often the button that gets clicked to open the dialog. I prevent the PostBack when it opens the dialog; then when the dialog button is clicked, I mimic the click of that button.
UPDATE:
I saw several people mention the following line of code
$(this).parent().appendTo(jQuery("form:first"));
I thought that's what you were attempting to do with your line of code:
$('.divInnerForm').append($(this).parent());
If that doesn't do the same thing, though, you would need to have the code to add your fields to the form.
I use the modal dialog and i need to add a row, otherwise i get the modal transparency over the close button!
var $ObjDialog = $("div[id*='div_MyPopup']");
$ObjDialog.dialog({
modal: true
});
$ObjDialog.parent().prev().appendTo($("form:first"));
$ObjDialog.parent().appendTo($("form:first"));

href link to trigger asp.net c# button event

I have a navigation bar consisting of list items. Right at the end of the nav bar I want a logout link:
//other links
...
<li>
logout
</li>
I have an event in my C# code called Logout_Click(object sender, EventArgs e) that I want to run when the user clicks the above navbar link, but obviously ordinary <a> tags don't trigger ASP.NET click events.
So I thought I'd be clever and create a HIDDEN <asp:Button> called logout that does trigger the Logout_Click function, and then get the JavaScript to click the button for me.. here is my code:
Log Out
<form runat="server">
<asp:Button ID="logout" runat="server" onclick="Logout_Click" Visible="false" />
</form>
But it still didn't work.
Can someone help me?
Try:
Log Out
Can you try without the Visible="false" on the asp:button?
And if it works hide it with css instead, style="display:none;"
I think the script needs the client side id of your asp.net control:
javascript:document.getElementById('<%=logout.ClientID').click()
Or you can use the __doPostBack function ...
http://wiki.asp.net/page.aspx/1082/dopostback-function/enter link description here
Why not you are using Asp.net LinkButton ?
It's easy to do this work with LinkButton.

Categories