asp:Button in jQuery dialog box not firing OnClick event - javascript

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"));

Related

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

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!

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);

OnClientClick not triggering on first click on button after postback

I have an ASP button. On click of it I am opening a pop-up after doing some validations using JavaScript.
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup()" meta:resourcekey="btnHistory" OnInit="btnHistory_Init"/>
function ShowHistoryPopup() {
var age = $get("<%= txtSomeTextBox.ClientID %>");
var str = "";
if (Validate(age)) {
str = 'ClService.aspx?id=' + 'Null,' + age.value;
window.open(str);
}
else {
return false;
}
}
I have a radio button. Based on selected index I need to enable disable the History button. Radio button has 3 options and on 3rd option page postback happens. I need to keep the button enable on 1 st option only. I have implemented this logic with the help of Java Script and some code on OnPreRender event(for post back case).
Now the problem I am facing is, if I select option 1 or 2 and click History button, OnClientCLick event is triggering. But if I select option 3(postback) and then navigate back to option 1, onClientCLick is NOT triggering for the very first time. But on clicking the History button 2nd time its working fine. Anyone having suggestions or solution for this problem?
If I understand your problem I think what's happening is you are posting back after the History Button click which isn't what you want (as there's no click handler). Using this code works for me:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True" GroupName="Radio1" />
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup();return false;" meta:resourcekey="btnHistory" />
<script type="text/javascript">
function ShowHistoryPopup() {
alert("Here");
}
</script>
All I've added is the return false; after ShowHistoryPopup();
Also, I've used alert here for the purposes of demo, in reality we should really be using console.log('Show my message');

css class applying after double-click on the asp.net button

i want to apply a class on a asp.net label when validation fails, everything is working fine but it is requiring double-click to apply the class. First click to show the error message of the required field validator and second click applies the class. I need it in one click. Please help
<script>
function Validate()
{
//for textbox
if ($('#<% =RequiredFieldValidator1.ClientID %>').css('visibility') == 'visible')
{
$('#<% =Label1.ClientID %>').addClass('error');
}
else
{
$('#<% =Label1.ClientID %>').removeClass('error');
}
}
</script>
<asp:Label ID="Label1" runat="server" CssClass="lbl" Text="Name"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="Validate()"
Text="Submit" ValidationGroup="txt" />
You need to call your Validate() function directly on the page load.
The code is currently doing exactly what you asked it to do, when the validator is visible(after first click), and button is clicked, change color.
Add code like this to call the function onload
window.onload = Validate();

Why is there no __doPostBack() JavaScript added to a CommandField's Update button in GridView when rendered to HTML

I have a basic GridView with a CommandField which uses the CommandField's in-built Edit, Cancel, Update and Delete buttons, with the ButtonType property set to "Image" (ImageButtons), defined as:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false"
OnRowEditing="gv_RowEditing" OnRowCancelingEdit="gv_RowCancelingEdit" OnRowUpdating="gv_RowUpdating" OnRowDeleting="gv_RowDeleting">
<Columns>
<asp:CommandField
ShowEditButton="true" ShowDeleteButton="true" ButtonType="Image"
EditImageUrl="~\Images\Icons\gridView_Edit.png"
CancelImageUrl="~\Images\Icons\gridView_CancelEdit.png"
UpdateImageUrl="~\Images\Icons\gridView_Update.png"/>
</Columns>
The server-side C# event handlers for the OnRowEditing, OnRowCancelingEdit, OnRowUpdating and OnRowDeleting events are working fine and are defined as:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e) { }
protected void gv_RowEditing(object sender, GridViewEditEventArgs e) { }
protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { }
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e) { }
When the page is rendered to HTML, the ImageButtons in the CommandField are rendered to the following (simplified) <input> tags:
<input type="image" name="ctl00$Body$gv$ctl02$ctl00" src="Images/update.png" alt="Update" style="border-width:0px;">
<input type="image" src="Images/delete.png" alt="Delete" onclick="javascript:__doPostBack('ctl00$Body$gv','Delete$0')" style="border-width:0px;">
<input type="image" src="Images/edit.png" alt="Edit" onclick="javascript:__doPostBack('ctl00$Body$gv','Edit$0')" style="border-width:0px;">
<input type="image" src="Images/cancel.png" alt="Cancel" onclick="javascript:__doPostBack('ctl00$Body$gv','Cancel$0')" style="border-width:0px;">
NOTE: In reality, only either Edit/Delete or Update/Cancel are rendered at any one time, depending on whether the GridView is in edit mode or not.
So, why does the rendered Update button not use ASP.NET's __doPostBack JavaScript function, when the Delete, Edit and Cancel buttons do?
How is it that the OnRowUpdating event is handled?
NOTE: When using the default ButtonType for the CommandField it does render __doPostBack, but when using ButtonType="Image" __doPostBack is not included.
Note that these 4 buttons are never displayed together, you have either "Edit" "Delete" or, after you click "Edit", you get "Update" "Cancel".
So just as you click your "Edit" button and the set of buttons changes from "Edit" "Delete" to "Update" "Cancel", your "Update" button WILL have the __doPostback attached to it.
The OnRowUpdating is then handled normally, by the doPostback just after you click the "Edit" button.
You can download one of my examples
http://www.ii.uni.wroc.pl/~wzychla/ra2829/example3a.zip
to see that. Just change the button type to Image in Default.aspx and attach your handlers to the grid.

Categories