ASP.NET web app confirmation box - Button.Click - c#

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.

Related

Dynamic ModalPopupExtender not firing the OK Click event

ASP.NET 4.7.2 Web Forms c# VS 2019
I am trying to use a modalpopupextender to prompt for new data for foreign key fields. Like the form itself, the MPE is built on the fly in code -- in this case the click handler for the hidden button that the Javascript fires off to build and show the MPE.
I read every single article on SO and the ASP forums and tried everything I saw there. No joy. I get the popup perfectly. Hitting OK closes the popup, but never fires the OK Event.
Here is the code:
//Building the form, we do this in OnInit:
// AJAX Update Panel
UpdatePanel PUP = new UpdatePanel()
{
ID = "PUP",
};
PlaceHolder.Controls.Add(PUP);
// HiddenField containing the field name to permit
// creating the correct modalpopup.
HiddenField HFPopupField = new HiddenField()
{
ID = "HF_POPUP"
};
PUP.ContentTemplateContainer.Controls.Add(HFPopupField);
// Create Hidden button to track the popup
Button BPopup = new Button()
{
ID = "BPOPUP",
UseSubmitBehavior = false
};
BPopup.Click += BPopup_Click;
BPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(BPopup);
// And create the background panel for the popup.
Panel PnlPopup = new Panel()
{
ID = "PNLPOPUP",
CssClass = "MpeBackground"
};
PnlPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(PnlPopup);
/// Event handler for hidden button.
protected void BPopup_Click(object sender, EventArgs e)
{
[snip -- code to get the dataset that is being filled]
UpdatePanel PUP = Placeholder.FindControlRecursive("PUP");
Table T = new Table()
{
CssClass = "PopupTbl"
};
TableRow TRTitle = new TableRow();
TableCell TCTitle = new TableCell()
{
CssClass = "PopupTitle",
ColumnSpan = 2
};
Label LPopTitle = new Label()
{
Text = [title of the popup]
};
TCTitle.Controls.Add(LPopTitle);
TRTitle.Cells.Add(TCTitle);
DataRow drData = null;
// Add Fields, and also the cancel and Add buttons
foreach (DataColumn DC in dsColumns.Tables[0].Columns)
{
TableRow TRColumn = [create a tablerow with 2 columns, a prompt and the input field]
if (TRColumn != null)
{
T.Rows.Add(TRColumn);
[snip]
}
} // end of foreach(DataColumn DC in dsColumns.Tables[0].Columns)
PnlWindow.Controls.Add(T);
TableRow TRButtons = new TableRow();
TableCell TCButtons = new TableCell()
{
ColumnSpan = 2,
CssClass="PopupButtons"
};
Button MPEBOK = new Button()
{
ID = "MPE" + sFieldName + "_MPEBOK",
Text = "OK",
CausesValidation = false,
UseSubmitBehavior = false
};
MPEBOK.Click += MPEBOK_Clicked;
TCButtons.Controls.Add(MPEBOK);
LiteralControl LCB = new LiteralControl()
{
Text = " "
};
TCButtons.Controls.Add(LCB);
//************************************************************
//*** Postback Trigger ***
//************************************************************
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger()
{
ControlID = MPEBOK.ID,
EventName = "click"
};
PUP.Triggers.Add(trigger);
//************************************************************
//*** Cancel Button ***
//************************************************************
Button MPEBuhBye = new Button()
{
ID = "MPE" + sFieldName + "_BUHBYE",
Text = "Cancel",
UseSubmitBehavior = false
};
TCButtons.Controls.Add(MPEBuhBye);
TRButtons.Cells.Add(TCButtons);
T.Rows.Add(TRButtons);
PnlPopup.Controls.Add(PnlWindow);
AjaxControlToolkit.ModalPopupExtender MPE = new AjaxControlToolkit.ModalPopupExtender()
{
ID = "MPE" + sFieldName,
PopupControlID = "PNLPOPUP",
TargetControlID = "BPOPUP",
BackgroundCssClass = "MpeBackground"
};
// Add the MPE to the UpdatePanel.
PUP.ContentTemplateContainer.Controls.Add(MPE);
// Show the modal popup extender.
MPE.Show();
}
protected void MPEBOK_Clicked(object sender, EventArgs e)
{
[snip - this never fires]
}
I cannot find out what is happening here. Can anyone see something hinky?
Thanks
John.
You can't add a server side button or inject a server side button into the page DOM.
When you drag a asp.net button onto the form, BOTH the "mypage.cs" and mypage.desinger.cs ARE updated. The wire up of the button occurs at design time, and you would have to modify mypage.desinger.cs ALSO and ADD a button event stub.
So you can't do this.
A compromise would be to also add some js and have that HTML button execute a .click() method of a hidden asp.net button you drop into that page (that would give you the post back, and the running behind of a separate button event code stub.
This event resolution occurs at compile time - not at page render time. You have to drop that button onto the page.
I suppose you could adopt a standard that you always place right below that "div" on the page the button (hidden with style=none. And then as noted, have your injected code along with some js execute a click on the hidden button. Or just have the js button code execute a __doPostback("some value") and pick this up in the page on-load event, and then call the routine (function) from on-page load event.
I think better would be to use a jQuery.UI dialog, as that dialog CAN say load + use another different web page into a “div” on the existing page. So you layout, make, and create the nice looking popup form as a separate web page. jQuery is able to remove the “form” and additonal tags out of that page load, and then inject it into the existing page. (that code would be rather hard to re-produce). so jQuery.UI is able to pop up that separate page. however, the buttons on that loaded page (into that div) of course can't really run any code behind in the current page. However, the buttons CAN run local js in the current page. Thus the actions of this injected page would be local to each page. But the popup would not be directly calling a code behind stub.
Now, to adopt jQuery.UI, then you also have to of course adopt jQuery. So that is two extra libraries you need. (but, jQuery you likely already have).
However, I suppose the whole point of using the ajax toolkit is to avoid jQuery.ui in the first place. To be fair, before jQuery.ui came along, that tool kit was REALLY impressive, and gave asp.net folks a REAL leg up on the competition. (and it tends to be MUCH less wiring up then say using jQuery.UI
So the AjaxToolkit in its heyday was impressive. Now, it of course showing its age, but I still use the kit, and this is especially the case for the AjaxFileUploader. And yes I do use the popups – even to this day. However, I find now that jQuery.UI dialogs are more flexible, and would be better in this case (because you want a on-the fly setup).
Also, having code behind buttons in even the jQuery.UI dialog, or in this case the ajax popup? Well, only the action button can run code behind. The cancel button of course will just dismiss the dialog. However, any button in the dialog that WILL run code behind? Well, that's ok, since you have a page post back, and it actually the page postback that BLOWS out the dialog anyway.

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

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

How to set Textbox's Text as an querystring argument for LinkButton without having codebhind file?

I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>

How can I change another page's dropdown in aspx?

I had a form which is called contact.aspx and it has a dropdown which includes user list.
I add below line to add user.
New User
and the javascript of insertUser is below:
<script type="text/javascript">
function insertUser() {
var win = window.open('stackoverflow.aspx?t=1', 'User Insert', 'width=800,height=600');
}
</script>
And when I click "New User", stackoverflow.aspx is opened and I want to enter new user data and click save.
After clicking save buton, how can I close stackoverflow.aspx and only refresh dropdown at the contact.aspx?
You can use the following Javascript code to close child window and refresh parent(ref):
window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
or you can do partial refresh. see here
you must stored variable in session , db or ...
and use this link.
http://forums.asp.net/t/1606853.aspx/1
Don't do this on different page, because you can't update your field from an other page. You can make ajax requests from the contact.aspx by intervals, and you can check the DB if there is a new user, and refresh it. But it's not a nice solution. So I suggest to make this registration (which is on stackoverflow.aspx) on contact.aspx, inside an iframe or just inside a div. You can hide each content in each action (when you are registering, hide the rest of content just display the registration fields, if you are done refresh the dropdownlist reset your registration fields and hide them, display the dropdownlist).With this approach you can refresh your dropdownlist, when you are done with registration.
To refresh dropdownlist make an ajax call, where you can get the new values from the db (there can be multiple new values submitted by different user at the same time) and then you cen refresh dropdown (wich is a select with options in HTML) But if you do this, you can get an eventvalidation error, which is a built in asp.Net feature (defends against xss attack). So the solution can be to make a full postback after registration, and refresh the values by server code, or don't use server control to dropdownlist, only html select, and fill it on document ready, and refresh it async by javascript or jQuery.
mmm, On the stackoverflow.aspx after user clicks save, it posts to the server, creates a new user and get a JSON representation of the object. then register a script to close the window and pass the json to the opener.
private btnSave_Click(object sender, EventArgs args)
{
//Save data
...
string objectJson = GetJSON(); // {"userId": 100, "name": "John Smith"}
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.opener.appendObject(" + objectJson + ") </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "RefreshScript", cstext1.ToString());
}
On the contacts.aspx have the following script:
<script type="text/javascript">
function appendObject(json) {
var obj = JSON.parse(json); //convert json to object
//Add item to the drop down list.
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = obj.name;
try
{
// for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
</script>
Didn't test it but I think it works.

User text input handling using TextBox

I have this control:
I'm trying to create a kind of validation, that whenever the user enters text to the TextBox, the "Add" button will be Enabled, and when the text is "" (null), the "Add" button is disabled.
I dont want to use validators.
here's the code:
protected void addNewCategoryTB_TextChanged(object sender, EventArgs e)
{
if (addNewCategoryTB.Text != "")
addNewCategoryBtn.Enabled = true;
else
addNewCategoryBtn.Enabled = false;
}
The problam is, that when the user enter's text, the "Add" button doesn't changes from disabled to enabled (and vice versa)...
any ideas?
Is it Web Forms? In Web Forms the TextChanged event of the TextBox won't fire by default.
In order to fire the event, you have to set the AutoPostBack property of the TextBox to true.
BUT, this would perform a HTTP post, what is kink of ugly, or you can wrap that in an UpdatePanel
A more elegant option, is to do that using jQuery, to do that in jQuery, you'll need some code like:
$(document).ready(function() {
$("#<%= yourTextBox.ClientID %>").change(function() {
var yourButton = $("#<%= yourButton.ClientID %>")
yourButton.attr('disabled','disabled');
yourButton.keyup(function() {
if($(this).val() != '') {
yourButton.removeAttr('disabled');
}
});
});
});
You'll need to accomplish this with Javascript, since ASP.NET is incapable of performing such client-side modifications. Think about it ... every time you pressed a letter inside the text box, it would have to postback and refresh the page in order to determine if the text box was empty or not. This is one way that ASP.NET differs from Winforms/WPF.
TextChanged events will make postback on server every time. You don't need to increase those request for such task.
You can use jquery to achieve this
var myButton = $("#btnSubmit");
var myInput=$("#name");
myButton.prop("disabled", "disabled");
myInput.change(function () {
if(myInput.val().length > 0) {
myButton.prop("disabled", "");
} else {
myButton.prop("disabled", "disabled");
}
});
JS Fiddle Demo
You just need to take care of elements Id when you are using Server Controls. For that Either you can use ClientID or set property ClientIdMode="Static"

Categories

Resources