Submit button does not work within popup window - javascript

I have a form within popup window something like that:
<div id="dialog" title="Rezerwacja">
<asp:TextBox ID="imieTextBox" runat="server" placeholder="ImiÄ™"></asp:TextBox>
<asp:TextBox ID="nazwiskoTextBox" runat="server" placeholder="Nazwisko"></asp:TextBox>
<asp:TextBox ID="emailTextBox" runat="server" TextMode="Email" placeholder="Email"></asp:TextBox>
<asp:TextBox ID="telefonKomorkowyTextBox" runat="server" TextMode="Phone" placeholder="Telefon kom."></asp:TextBox>
<div id="plansza"></div>
<asp:Button ID="rezerwujButton" runat="server" Text="Zarezerwuj" OnClick="rezerwujButton_Click" />
</div>
And JavaScript:
$(document).ready( function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: {
effect: "puff",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$( ".opener" ).on( "click", function() {
$( "#dialog" ).dialog( "open" );
});
});
So I have to behind code:
protected void rezerwujButton_Click(object sender, EventArgs e)
{
rezerwacje nowaRezerwacja = new rezerwacje();
nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = telefonKomorkowyTextBox.Text;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();
}
And there is the problem, submit button "rezerwujButton" does not work. It look like a unclickable or something like that... I'm clicking on it and nothing do... Not refresh page or anything...
When I going to use that form without popup window, It work but within popup not.
I tried to set usesubmitbehavior="false" but when I did it, button worked, send something but every field was blank... I mean when i tried to get something like that: imieTextBox.Text It will be blank... Always...
Any ideas?
#edit
I don't know what Do I do wrong?
Always a fields from form is blank...
Anybody can tell me how can I use correct this __PostBack? Because I have to do something wrong...
I added to button UseSubmitBehavior="fase" and in function PageLoad I got something like that:
if (Page.IsPostBack)
{
rezerwacje nowaRezerwacja = new rezerwacje();
nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = telefonKomorkowyTextBox.Text;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();
}
For example imieTextBox.Text is always blank... I don't know why...?
edit
Im done. I change the way to get modal window. I used popup window which not moving modal div anywhere and It working.

The reason of the "nothing happens" behaviour is the fact that jQuery-UI dialog widget moves the DOM-element, which is converted to a dialog (in your case - $("#dialog")), to body. After this, the submit button is not inside a form tag anymore, and clicking it does not cause any submission.
It will still work if the whole form is inside the dialog content:
<div id="dialog" title="Rezerwacja">
<form ...>
...
<asp:Button ID="rezerwujButton" runat="server" Text="Zarezerwuj" OnClick="rezerwujButton_Click" />
</form>
</div>

You can try putting your rezerwujButton_Click method into PageMethods
[ScriptMethod, WebMethod]
public string RezerwujCall() {
// logic here
return "ok";
}
Then in your js:
<script type="text/javascript">
function rezerwuj_clicked() {
PageMethods.RezerwujCall(function (response) { if(response == "ok"){} }, function(response){ console.log("failed"); });
}
</script>
This will require to change OnClick="rezerwujButton_Click" into OnClientClick="rezerwuj_clicked()"

Related

ASP.Net jQuery dialog only shows up the first time it's hovered over

I have a User Control which has an UpdatePanel, inside of which is a Repeater, inside of which are Linkbuttons:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="RelatedEntityControl.ascx.cs" Inherits="MyApp.Controls.Layout.RelatedURLControl" %>
<asp:UpdatePanel ID="RelatedObjectsPanel" runat="server">
<ContentTemplate>
<script type="text/javascript">
function openPopup(url, h, w, t, link) {
{
if (url != null && h != null && w != null && t != null && link != null) {
var btn = document.getElementById(link);
var top_distance = btn.getBoundingClientRect().top;
var left_distance = btn.getBoundingClientRect().left;
var myDialogX = left_distance - w/2;
var myDialogY = top_distance;
$('#PreviewWindow').html('<iframe style="border: 0px; " width="100%" height ="100%" src="' + url + '"> </iframe>');
$("#PreviewWindow").dialog({
title: t,
modal: false,
autoOpen: true,
height: h,
width: w,
closeOnEscape: true,
position: [myDialogX, myDialogY],
dialogClass: 'dialog_fixed,ui-widget-header',
open: function (event, ui) {
$(this).css('overflow', 'hidden'); //this line does the actual hiding of the vertical scrollbar
}
});
}
};
}
</script>
<script type="text/javascript">
$(function () {
var btn = $('.previewLink');
btn.hoverIntent(function (e) {
e.target.click();
}, function () { });
});
</script>
<asp:Panel ID="URLPanel" runat="server" Visible="false">
<asp:CollapsiblePanelExtender ID="URLsCollapsiblePanel" runat="server" CollapseControlID="URLsLabel" ExpandControlID="URLsLabel" TargetControlID="URLsPanel" TextLabelID="URLsLabel"
CollapsedText="[ + ] Related URLs" ExpandedText="[ - ] Related URLs" />
<asp:Label ID="URLsLabel" runat="server" CssClass="collapsiblePanelHeader" Text="" Width="90%"></asp:Label>
<asp:Panel ID="URLsPanel" runat="server" CssClass="collapsiblePanelContent" style="height: auto;">
<asp:Repeater ID="URLsLocalRepeater" runat="server" OnItemDataBound="LocalRepeater_ItemDataBound" ItemType="SSPS.Models.Relationships.RelatedURL">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="HyperLink1" Text='<%# Item.Title %>' NavigateUrl='<%# Item.ActualLink %>' runat="server" Target="_blank" ToolTip='<%# Item.ToolTip %>'></asp:HyperLink> <asp:LinkButton ID="PreviewButton" runat="server" CausesValidation="false" Text="preview" OnClick="PreviewButton_Click" Font-Size="X-Small" CssClass="previewLink"></asp:LinkButton>
<div id="PreviewWindow"></div>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</asp:Panel>
</asp:Panel>
</ContentTemplate>
The Javascript snippet attaches a hoverIntent function to the LinkButtons so that when the user hovers over them, I catch that hover, then cause the LinkButton to click(). From there we go server-side where I do some processing for the Linkbutton and eventually end up doing this to the LinkButton:
protected void PreviewButton_Click(object sender, EventArgs e)
{
//figure out the loc, url and so forth
string loc = ResolveUrl("~/PreviewWindow.aspx");
loc += "?url=" + url.ActualLink;
ScriptManager.RegisterStartupScript(this, this.GetType(), "dlg", "openPopup('" + loc + "', " + url.HintHeight + ", " + url.HintWidth + ", '" + url.Title + "', '" + previewButton.ClientID + "')", true);
return;
}
Now, I load my page, with its associated UserControl, and my LinkButtons just sit there staring at me until I hover over them. Once I do that, then up pops the jQuery dialog and shows me the url I asked for.
All is well so far. But once I close the dialog, everything breaks down. I hover over a LinkButton again (same or different one, doesn't matter) and nothing happens. The server-side PreviewButton_Click() function never gets called, and everything just sits there stupidly and stares at me.
To try to narrow down the problem, I removed the Javascript that sets up the hoverintent function. Without that I have to actually click on the LinkButton, but that never fails to bring up the dialog, no matter how many times I click it, so it seems that there's a problem in the javascript portion.
I, with my not-exceedingly-in-depth knowledge of javascript, am thinking that there is some action that is messing up the javascript. But I'm not sure where to look. I've looked at it in Chrome's inspect window, but there doesn't seem to be any errors in the javascript.
Any suggestions?
Update: After trying suggesting from #mjw and #WevDev, I'm seeing even more evidence of strange behavior. I found that anything I do in that UserControl that causes a postback will kill the jquery dialog. So it looks indeed like the postback is causing a loss of the javascript that calls the hoverIntent. But nothing I try will fix that loss of the javascript.
It has an issue because
ASP.Net page lifecicle.
First hover works because you register hover event handler with this js code
$(function () {
var btn = $('.previewLink');
btn.hoverIntent(function (e) {
e.target.click();
}, function () { });
});
After postback ASP.NET rerenders everything inside updatepanel, so previously registered handlers are not valid anymore. It means that var btn = $('.previewLink') (previously selected elements) have nothing to do with newly rendered elements.
It is the same as if you have <a> which has a click handler, then you remove <a> and create new <a>. HTML will look as was before but click handler won't work anymore, because it has nothing to do with newly created element.
$(function(){ .... }); this is a shorthand for document ready. So it fires only once when document is ready. After your postback this function doesn't get triggered. Hence you have newly created <a> but there is no js code to register handlers.
So, move script block down below panels (but keep inside updatepanel), and remove document ready shorthand. e.g.
<script>
............
var btn = $('.previewLink');
btn.hoverIntent(function (e) {
e.target.click();
}, function () { });
</script>
Hope this helps
[UPDATE]
Try this:
protected void Page_PreRender(object sender, EventArgs e)
{
var script = #"
var btn = $('.previewLink');
btn.hoverIntent(function (e) {
e.target.click();
}, function () { });
";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "someKey",
script, true);
}
Hope this helps

Jquery Confirm Dialog box disappears in aspx

I am using custom jquery confirm dialog box on button click in aspx page. Problem is that when I am clicking the button the dialog box is coming but automatically closes after some seconds due to autopostback. How to resolve it?
Here is my code...
<script>
$(function confirmation () {
$('#btnUpdate').click(function () {
$('#dialog').dialogBox({
content:'Are you sure to update..!!',
hasClose: true,
effect: 'fade',
hasBtn: true,
confirm: function () {
$('#message').dialogBox({
title: 'Confirmation..',
content: 'Updated Sucessfully..!!',
hasClose: true
})
}
})
})
})
</script>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" OnClientClick="return confirmation()" />
Try adding UseSubmitBehavior="false" in <asp:Button> to prevent the button triggering the postback.
Sample:
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" OnClientClick="return confirmation()" UseSubmitBehavior="false" />
Add the event parameter to your click handler, and then cancel (prevent) the default action:
$('#btnUpdate').click(function (e) {
e.preventDefault();
})
Do the following changes:
Cancel the default behavior of the asp.
Replace the #btnUpdate with #<%=btnUpdate.ClientID%>
Call the postback when the confirm is true.
Below is the updated code:
$("#<%=btnUpdate.ClientID%>").click(function(){
event.preventDefault();
$('#dialog').dialogBox({
content:'Are you sure to update..!!',
hasClose: true,
effect: 'fade',
hasBtn: true,
confirmValue: 'I am sure',
confirm: function(){
__doPostBack($('#<%=btnUpdate.ClientID %>').attr('name'), '');
}
});
})

How does user confirmation message box work in ASP.Net

How does the client know to send request to server only when the confirmation box result is ok and stay on page if cancelled?
Also, is this mechanism any different in ASP.Net and ASP.Net MVC?
The responses I got seem to tell me how to implement the functionality.
I want to know the internal working of when user clicks OK/cancel what happens internally. How does browser come to know it has to proceed to server call or close itself and do nothing?
You can use simple confirm box
$("#callConfirm").on("click", function(e) {
if(confirm('Are you sure'))
alert('Yes');
else
alert('No');
});
JSFIDDLE
Try This
<script>
function CallConfirm()
{
if(confirm('Are you sure'))
//do your stuff
else
return false;
}
<script />
and on asp button write like this
<asp:Button id="Click" runat="server" onclientclick="return CallConfirm();" onclick="btn_Click"/>
you can use bootstrap in asp.net and it will help you give new look and help you in lots of other things,see this http://getbootstrap.com/ and u can use bootstrap confirmation box.
<asp:button
id="Button1" runat="server" text="Button" xmlns:asp="#unknown">OnClientClick="return confirmation();" onclick="Button1_Click"/>
</asp:button>
<script type="text/javascript">
function confirmation() {
if (confirm('are you sure you want to delete ?')) {
return true;
}else{
return false;
}
}
</script>
I write this Jquery code in the aspx page for button.
Steps:
Add a button for which you want to have a confirm box, add its jquery and div to show the confirm box.
Register the script for button on Page_Load, and write the methods which will bind this script on button.
Also do not forget the server side method or event for button click, which will be continued after OK confirmation from confirm box.
If cancel is clicked, nothing will happen and div will be closed.
<script type="text/javascript">
function FileItem(callBackFunction, title, content) {
$("#File-confirm").html(content).dialog({
autoOpen: true,
modal: true,
title: title,
resizable: false,
height: 140,
close: function (event, ui) { $(this).dialog("destroy"); },
buttons: {
'Ok': function () {
callBackFunction(); $(this).dialog("destroy");
},
'Cancel': function () {
$(this).dialog("destroy");
}
});
}
}
where SaveBtn is the button in the UI:
<asp:Button ID="SaveBtn" runat="server" Text="File" OnClick="SaveBtn_Click"/>
<div id="File-confirm" style="display: none">
</div>
Again the code behind:
FileConfirmRequest(SaveBtn, "Confirm", "Are you sure you want to file the changes?");
// In the Page_Load, write the above code
//Use this method later on the page
protected void FileConfirmRequest(Button control, string title, string message)
{
string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
string function = String.Format("javascript:FileItem(function() {{ {0} }}, '{1}', '{2}'); return false;", postBackReference, title, message);
control.Attributes.Add("OnClick", function);
}
Now, The Onclick of the Button:
protected void SaveBtn_Click(object sender, EventArgs e)
{
//Do what you want to after OK Click from the confirm box
}

How to Trigger LinkButton Postback after Confirmation using jQuery UI Dialog?

I want a LinkButton to popup a jQuery UI dialog that prompts the user to confirm the action. If the user hits OK, then I'd like the action to continue by posting back to the server.
I ended up creating two links: One is regular HTML that invokes my confirmation dialog. And the other is a regular LinkButton server control that is hidden, and that I want to invoke if the user confirms the dialog box.
The two links look like this:
<a id="preEnterOperations" href="#">
Enter Operations
</a>
<asp:LinkButton ID="lnkEnterOperations" runat="server"
OnClick="lnkEnterOperations_Click" Style="display:none">
Enter Operations
</asp:LinkButton>
And here's my JavaScript:
$(function () {
$('#preEnterOperations').on('click',
function (e) {
var confirmDialog = $('#enterOperationsConfirmationDialog');
confirmDialog.dialog({
modal: true,
buttons: {
Ok: function () {
confirmDialog.dialog("close");
confirmDialog.data('confirmed', '1');
$('#<%= lnkEnterOperations.ClientID %>').click();
},
Cancel: function () {
confirmDialog.dialog("close");
}
}
});
return false;
});
});
Everything seems right. The confirmation dialog pops up as expected. I can see my Ok handler runs if the user hits Ok. But the line $('#<%= lnkEnterOperations.ClientID %>').click(); doesn't do a thing! I've tried numerous variations on this line and the effect is always the same: nothing.
Can anyone help me see how I can execute a LinkButton postback if the user confirms the dialog box?
You can replace the following line:
$('#<%= lnkEnterOperations.ClientID %>').click();
With:
__doPostBack('<%= lnkEnterOperations.UniqueID %>', '');
That should do the trick.
Ok: function () {
confirmDialog.dialog("close");
confirmDialog.data('confirmed', '1');
$('#<%= lnkEnterOperations.ClientID %>').click(function(){
__doPostBack('<%= lnkEnterOperations.UniqueID %>', '');
});
},
Cancel: function () {
confirmDialog.dialog("close");
}
May be this can help.
You can replace "$('#<%= lnkEnterOperations.ClientID %>').click();"
with <%=Page.ClientScript.GetPostBackEventReference(lnkEnterOperations, "") %>

Unable to get javascript to do button click from child iframe

I'm playing around with the Jquery UI dialog. I have a page with a gridview, a button that refreshes the gridview and a link. When you click a link, a dialog window popup up with the details of the record.
When I press save on the child page, I have the child page calling a javascript function from the parent page. In this function, it tried to do the button click event but it doesn't seem to be working.
If you look at the showThanks function below,
The alert works, the button text changes but the button click doesn't work.
Could this be a security feature? Both pages are on the same page right now.
hmm any clue?
Thanks
Edit - if you click the button manually, it changes the grid (in the button event handler). Yet, the jquery doesn't seem to be going in the button's event handler and the grid doesn't change.
Parent page html
<asp:GridView ID="gv" runat="server" />
<asp:Button ID="btnRefresh" runat="server" />
<a id="popoutUsers" href="popup.aspx?page=Bob" class="OpenNewLink">CLICK ME</a>
<script type="text/javascript">
$(function () {
$('.OpenNewLink').click(function () {
var url = $(this).attr('href');
var dialog = $('<div id="modal"></div>').appendTo('body')
$('<iframe id="site" src="' + url + '" />').dialog({
modal: true
, close: function (event, ui) {
// remove div with all data and events
dialog.remove();
}
});
return false;
});
showThanks = function () {
alert("Thanks");
var button = $("#btnRefresh");
button.val("hello"); //This works
button.click(); //Nothing seems to happen
// button.trigger("click"); (Tried trigger as well but no luck)
};
});
</script>
Child page
<div>
Why hello there
<asp:Button ID="btnBob" runat="server" Text="click me" />
</div>
<script type="text/javascript">
$(function () {
$('#btnBob').click(function (e) {
e.preventDefault();
window.parent.showThanks();
window.parent.$('.ui-dialog-content').filter(function () { return $(this).dialog('isOpen'); }).dialog('close');
return false;
});
});
</script>
So decided to do a new round of google searching and found this link Html Button that calls JQuery and does not post back
I changed my button to the following (added the UseSubmitBehavior)
and now it works. Hopefully I didn't waste people's time...

Categories

Resources