pop up does not go for post back in asp.net - c#

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>

Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

Related

ASP.NET web app confirmation box - Button.Click

I have an ASP.NET 4.5 web app that contains a form where the user can add some data and I have a button that I want to save the data in the database.
When the user presses this button, the first thing I do is search if there already exists a record for a specific item. If there is, I want to show a confirmation box where I'm letting the user know: "This record already exists. Do you want to update it?". If the user presses YES, I want to do an UPDATE, else I will do an INSERT. The problem is with this damn confirmation box.
What I have so far:
In aspx.cs:
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Write("YES");
}
else
{
Response.Write("NO");
}
}
In aspx I have:
<script>
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Record already exists. Do you want to update it?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
and I added a button:
<asp:Button ID="alertBtn" runat="server" OnClientClick = "Confirm()" OnClick="OnConfirm" Text="" style="display:none"/>
If I remove the style and run the app, when I click on this button it works perfectly. The confirmation box shows up, when I click YES it calls a function, when I click NO it calls another function.
But how do I click on this button from code? Nothing works!
I tried with:
1) alertBtn.Click += new EventHandler(this.OnConfirm);// doesn't do anything
2) ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "somekey", "Confirm();", true);// I was only able to run the Confirm() method, but it didn't call the OnConfirm method which is on the server.
3) Following step 2, I tried adding a call from js to c# in the Confirm() method: document.getElementById('<%=alertBtn%>).OnClick // this didn't work either
So I just want to do a Button.Click from code behind in order to trigger the Confirm() method which will open a confirmation box and after I click YES/NO, the OnConfirm method from the server should call the appropriate function based on this YES/NO value. If you have another solution besides the one with using a button, I'm open to new ideas.
Update
To better explain my problem, I added this demo link. I want to achieve the same thing without having to click on a button, just from code.

ASp.net Button on jqueryui Dialog causes all from data to reset. UsesubmitBehavior=False, and databind in (!ispostback)

So I've been struggling with this for a couple days now. I have a login page, that checks if the user is logging in for the first time, and if so, it shows a jqueryui Dialog box asking the user to pick their security questions. The Dialog is simple, three dropdowns, three text boxes, and a continue and cancel button. The dialog is displaying find, and when you click continue, the data is saved to the database, but it only saves the default values of the dropdownlists, and it doesnt save the text from the text boxes. It seems to me like the form is posting back before the data saves, and then saves the blank/default content. I've tried everything I can find on the internet to fix this. As of right now, I'm launching the dialog box on page load for testing purposes. Code Below:
Javascript:
function validateQuestions() {
var q1Index = $('#<%= ddlQuest1.ClientID%>').get(0).selectedIndex;
var q2Index = $('#<%= ddlQuest2.ClientID%>').get(0).selectedIndex;
var q3Index = $('#<%= ddlQuest3.ClientID%>').get(0).selectedIndex;
"<%=Q3Index%>" = q3Index;
var label = document.getElementById('<%= _lblQuestError.ClientID%>');
label.style.display = 'none';
if (q1Index == q2Index || q1Index == q3Index || q2Index == q3Index) {label.style.display = 'block';}
else {label.style.display = 'none'}
return false;
}
function validateAnswers() {
var ans1Text = $('#<%= txtAnswer1.ClientID%>').val();
var ans2Text = $('#<%= txtAnswer2.ClientID%>').val();
var ans3Text = $('#<%= txtAnswer3.ClientID%>').val();
var ans1error = document.getElementById('<%= _lblAns1Error.ClientID%>');
var ans2error = document.getElementById('<%= _lblAns2Error.ClientID%>');
var ans3error = document.getElementById('<%= _lblAns3Error.ClientID%>');
ans1error.style.display = 'none';
ans2error.style.display = 'none';
ans3error.style.display = 'none';
if(ans1Text=""){ans1error.style.display = 'block';}
else if(ans2Text=""){ans2error.style.display = 'block';}
else if(ans3Text=""){ans3error.style.display = 'block';}
else { ans1error.style.display = 'none'; ans2error.style.display = 'none'; ans3error.style.display = 'none'}
return false;
}
function cancel() {
$("#_dlgQuest").dialog('close');
return false;
}
function showDialog() {
var secQuestDlg = $('#_dlgQuest').dialog({
bgiframe: true,
height: 350,
width: 900,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: ".8"
}
});
secQuestDlg.parent().appendTo('/html/body/form[0]');
}
Button aspx: <asp:Button ID="_dlgbtnContinue" ToolTip="Continue" runat="server" Text="Continue"
UseSubmitBehavior="false" OnClick="_dlgbtnContinue_Click" CausesValidation="false" />
PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlQuest3.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest1.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest2.Attributes.Add("onchange", "javascript:validateQuestions();");
txtAnswer1.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer2.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer3.Attributes.Add("onblur", "javascript:validateAnswers();");
List<String> lstQuestions = QuikDrawServiceHelper._QuikDrawClient.GetQuestions();
ddlCountry.Focus();
FillQuestions();
ClientScript.RegisterStartupScript(GetType(), "hwa", "showDialog()", true);
}
}
Fillquestions:
try
{
foreach (string s in lstQuestions)
{
if (s.Equals(Customer.Quest1Code))
{
q1 = s;
}
if (s.Equals(Customer.Quest2Code))
{
q2 = s;
}
if (s.Equals(Customer.Quest3Code))
{
q3 = s;
}
}
}
catch (Exception ex)
{
}
Complete Click Event:
protected void _dlgbtnContinue_Click(object sender, EventArgs e)
{
Customer = CompanyServiceHelper._CompanyClient.GetCustomerByID(Convert.ToInt32(Session["CustomerID"].ToString()));
if (Session["FirstLogin"] == "Yes")
{
Customer.Quest1Code = ddlQuest1.SelectedValue;
Customer.Quest1Ans = txtAnswer1.Text;
Customer.Quest2Code = ddlQuest2.SelectedValue;
Customer.Quest2Ans = txtAnswer2.Text;
Customer.Quest3Code = ddlQuest3.SelectedValue;
Customer.Quest3Ans = txtAnswer3.Text;
CompanyServiceHelper._CompanyClient.AddQuestionsForCustomer(Customer);
Session["FirstLogin"] = "Yes";
Session["CustID"] = Customer.CustID;
}
I've tried linkbuttons as well, and i get the same thing. Any help would be greatly appreciated.
The root cause of the problem you are facing is the fact that the dialog is made "display:none" when popup disappears, and this resets all the values inside the dialog, making them not accessible on server. Despite "runat=server", form fields are not accessible on server bcz of "display:none", making you think the values are never set !!
Seems like when you click the dlgbtnContinue button it is still not doing a postback, therefore you get the !isPostBack all over, and then resets the values. After this, the _dlgbtnContinue_Click event is getting triggered, saving the blank values. Maybe try to check in !isPostBack if also the values in the DropDown are not the default, meaning that if they are not the default values you do not want to get inside that if again. Just an idea... It would be good to have the _dlgbtnContinue_Click code. Good luck.

How To set Default Button for ENTER key

We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.

Change page state with JavaScript, old state gets recalled on postback

Basically we have the "illusion" of an notification message box that exists as .Visible = false in the MasterPage. When it comes time to display a message in the box, we run a method that looks like this:
public static void DisplayNotificationMessage(MasterPage master, string message)
{
if (Master.FindControl("divmsgpanel") != null)
{
master.FindControl("divmsgpanel").Visible = true;
}
if (master.FindControl("divdimmer") != null)
{
master.FindControl("divdimmer").Visible = true;
}
TextBox thetxtbox = (TextBox)master.FindControl("txtboxmsgcontents");
if (thetxtbox != null)
{
thetxtbox.Text = message;
}
}
Basically through our designers awesome CSS voodoo, we end up with what appears to be a floating message box as the rest of the page appears dimmed out. This message box has a "Close" button to dismiss the "popup" and restore the dimmer, returning the site to the "normal" visual state. We accomplish this with JavaScript in the MasterPage:
function HideMessage() {
document.getElementById("<%# divmsgpanel.ClientID %>").style.display = 'none';
document.getElementById("<%# divdimmer.ClientID %>").style.display = 'none';
return false;
}
and the button's declaration in the .aspx page calls this HideMessage() function OnClientClick:
<asp:Button ID="btnmsgcloser" runat="server" Text="Close" style="margin: 5px;"
OnClientClick="return HideMessage()" />
The problem:
All future postbacks cause the MasterPage to "remember" the state of those divs from how they were before the HideMessage() JavaScript was executed. So in other words, every single postback after the initial call of the DisplayNotificationMessage() method causes the page to return to divmsgpanel.Visible = true and divdimmer.Visible = true, creating an endlessly annoying message box that incorrectly pops up on every postback.
The question:
Since we want the Close function to stay client-side JavaScript, how can we "notify" the page to stop reverting to the old state on postback, for just these two divs?
Can you try setting them to Visible = false in Master_Page Load event? It should hide them and reshow them just when you call DisplayNotificationMessage

Delete does not ask for confirmation

When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"

Categories

Resources