As I was a Windows programmer it was so easy to show a message box on a form.
But on an ASP.NET page I don't know how can I show it?
Actually I have some condition and based on that I want to show a message box to the user to get his/her response and based on that response I want to continue.
For example I want to ask the user "Do you want to continue?" with two buttons "Yes" & "No".
You can do this using JavaScript. Include this snippet in your code -
<script type='text/javascript'>
document.getElementById("someButtonId").onclick = function() {
var confirmation = window.confirm("Are you sure?"); //confirmation variable will contain true/false.
if(confirmation) { /* Write code for Yes */ }
else { /* Write code for No */ }
}
</script>
The only way to show a Yes No dialog, is to design a custom one (Javascript confirm can only produce OK and Cancel).
Luckily, ASP.NET Ajax controls (Ajaxcontroltoolkit) makes this job easy, as you can have a panel as your messagebox with the buttons you want, and have a ModalPopupExtender to imitate a dialog.
EDIT:
For what you ask with javascript, you can do it (and it is a much simpler solution than any seen so far), but prepared to only have OK and Cancel as the two possible answers. UI Designer Nightmare ! :(
Basically, have the following two properties in your aspx page for that button or whatever:
onClientClick = "javascript:confirm('you sure you wanna do this?');" onClick="myButton_Click"
onClick will only run if OK is pressed on the msg dialog.
window.alert(); window.confirm(); and window.prompt();
This is I guess what you are looking for.
You can use
window.confirm
for this.
It displays a modal dialog with a message and two buttons, OK and Cancel.
window.confirm
Eg:
if (window.confirm("Want to see my mood ring?"))
{
// wants to continue
}
else
{
// cancel the action
}
Edit:
You can also develop custom message boxes using jQuery. Here is a nice one
jQuery Impromptu
.aspx markup
<head runat="server">
<title>Sample Page</title>
<script type="text/javascript">
function doSubmit(){
var confirmation = window.confirm("Are you sure?");
document.getElementById("HiddenField1")["value"]=confirmation;
return true;
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="return doSubmit()" >
<div>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (HiddenField1.Value == "true")
{
}
else
{
}
}
If you REALLY want to have "yes"/"no" buttons (or any buttons that are not your standard OK/Cancel for that matter) you can do the following:
Main page:
<html>
<body>
<script>
function ShowYesNo() {
var answer = window.showModalDialog("myModalDialog.htm", '', "dialogWidth:300px; dialogHeight:200px; center:yes");
document.write('Clicked yes');
} else {
document.write('Clicked no');
}
}
ShowYesNo();
</script>
</body>
</html>
MyModalDialog.htm
<html>
<body>
<p> Do you want to proceed?" </p>
<input type = "button" id = "buttonYes" value = "Yes" onclick = "buttonOnClick('yes')">
<input type = "button" id = "buttonNo" value = "No" onclick = "buttonOnClick('no')">
<script type = "text/javascript">
function buttonOnClick(message) {
window.returnValue = message;
window.close();
}
</script>
</body>
</html>
You can use the confirm JavaScript function, but that will be limited to OK/Cancel as options. If this is not what you want, you can lean on the VBScript MsgBox client-side function. Bear in mind that doing so will only work with Internet Explorer.
function PerformDelete(id)
{
if(confirm("I am about to delete this record. Is this ok?"))
{
//your code here
}
}
i have a solution for you, may be it help you, for using that same message box or conformation dialog of c# in Asp.Net, first you should add namespace,
Using System.Windows.Forms;
then, where you want to call a message box or conformation dialog, you can just call it as simple as in c#, like:
DialogResult dialogResult = MessageBox.Show("Are you shure?", "Some Title",
MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Response.Redirect("Page.aspx");
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("You Select Nothing to do... :(");
}
I think, I explained properly, sorry for any mistake....
Related
I'm looking for a custom user control similar to http://www.how-to-asp.net/messagebox-control-aspnet/ but having the ability to be displayed as a popup. The message box should have the capability of being invoked from code behind in asp.net 4 with event hooks to bind the "ok" and "cancel" button.
I'm familiar with Ajax Toolkit and JQuery.
A reference and or sample in a similar direction would be very helpful.
Thanks!
Use jQuery UI. They have great examples. I use the dialog all the time.
You can view their source and here is an example of one.
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
You are able to customize this anyway you want. The link will show you how to do this.
EDIT: Since you want to open it in the behind code, I'll show you my jQuery and how I call it in the behind code. I use this to send emails.
function sendEmail() {
$("#email").dialog({
modal: true,
width: 700,
buttons: {
"Send": function () {
var btn = document.getElementById("<%=lbSend.ClientID %>");
if (btn) btn.click();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
);
jQuery("#email").parent().appendTo(jQuery("form:first"));
};
Then in the behind code.
protected void btnEmail_Click(object sender, EventArgs e)
{
//this calls the jQuery function.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "sendEmail();", true);
}
In my experience, it's usually a sign of a bad design if you want to open something on the client side from the server side code behind. Are you sure that's what you need?
But assuming you do, you can use the ModalPopupExtender from the Ajax Control Tookit. It can be opened from client or server side. Here's a sample:
<ajaxToolkit:ModalPopupExtender ID="MPE" runat="server"
TargetControlID="LinkButton1" ClientIdMode="Static"
PopupControlID="Panel1" />
The PopupControlID should be the ID of a panel that you want to appear as a popup. You can put buttons on that panel if you need to. From the code behind, it's as simple as this...
MPE.Show();
To show it from JavaScript (assuming jQuery), make sure you set the ClientIdMode to Static, then call it...
$('#MPE').show();
public void Message(String msg)
{
string script = "window.onload = function(){ alert('";
script += msg;
script += "');";
script += "window.location = '";
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
}
I'm maintaining an ASP .Net Application that seems somehow duplicate a records e.g. using a page add-user. I was unable to reproduce but I found some code that do something crazy like, on submit:
if(crazy-code()){
__doPostBack() // 2nd
}
and crazy-code also do something like
function crazy-code()
{
...
__doPostBack() // 1st
...
return true;
}
To find out this piece of code is causing the problem, I have been trying to fire both __doPostBack but I was unable to do it.
In theory, what should always happens is when it fire the (1st) __doPostBack, it should send the request and stop/ignore any client code afterward.
if __doPostBack is fired twice, what will be the reasons? the browsers? the speed? ???
The __doPostBack() call will submit the form and it should not call the second one.
I might be wrong, but I think you can reproduce your issue if you hit "Submit" on your web page and after the page reloads hit "F5". Depending on the browser, it will ask something like "resend the from data?". Select "Yes" and check whether your records have been duplicated.
In any case, i think you need to add the checks for duplicated values when you insert the data on the server side.
I was able to create a testing code. in FF and chrome seems to work fine (1 submit) but the IE9 (and compatibility version) seems to hit 1, 2 or 3 times.
NOTE: the submit() cause the postback.
CASE 1. delay in Javascript
Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>testing</title>
<script type="text/javascript">
function submitForm() {
document.forms[0].submit();
alert("delay");
document.forms[0].submit();
}
</script>
</head>
<body>
<form id="form1" name="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="220px"></asp:TextBox>
<button onclick="submitForm(this)">CLICK</button>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
incrementVal();
}
}
private void incrementVal()
{
var val = (int)(Session["val_" + TextBox1.Text] ?? 0);
val++;
Label1.Text += TextBox1.Text + ": " + val.ToString("00") + " - " + DateTime.Now.ToLongTimeString() + "<br/>";
Session["val_" + TextBox1.Text] = val;
}
CASE 2: Slow Response
remove JS Alert:
function submitForm() {
document.forms[0].submit();
document.forms[0].submit();
}
add delay in the server side:
if(IsPostBack)
{
incrementVal();
Thread.Sleep(500);
}
I'm trying to get a sequence of things to happen in the correct order, but no luck. What I have is a number of fields with asp:ReuiredFieldValidators and asp:ValidatorCallout to display validation messages. This is triggered with a button Save with validation="true".
If all validates, it should display a modal dialog asking for two choises on how to save the data. No matter the answer, it should always continue at this stage to code behind save function.The AjaxToolkit_ModalPopupExtender is connected to the same save button.
What happens is that the validation callouts and modal dialog is shown at the same time.
Searched for tips and help but haven't found any, for me, helpful! Most grateful for any help!
Cheers
/Johan
You can show the ModalPopup from codebehind(in BtnSave.Click-handler) if the page is valid:
Page.Validate("YourValidationGroup");
If(Page.IsValid){
ModalPopup1.Show();
}
Therefor you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
You must move to Code Behind only when the Page is validated in client side. You can do it using OnClientClick of button
<asp:Button ID="ShowDialog" onClientClick = "return ValidatePage();"
runat="server" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
return true;
}
else {
// do something else
alert('Page is not valid!');
return false;
}
}
</script>
I have an Asp.Net web page, having the common Asp.Net form. The outer "border" of the page (i.e. main menu, header, ...) is build using normal Asp.Net code using a master page. The content of that page uses jQuery to display dynamic forms and to send data to the server.
If I push the return key on that page, I jump to a (more or less) random page - which is not what the user expects. ;-)
There are some text areas and the user must be able to enter line breaks. Otherwise it would be fine to disable the return key completely. Any bullet proof way to do that?
I found some solutions on the web, which capture the keypress event and ignore \x13, but that does not really work. It works as long as the page has just loaded, but as soon as I have clicked on some elements, the return key behaves as usuall.
Any hint would be really appreciated!
Achim
Here is some script I put together yesterday night but was not able to post it as my laptop ran out of battery :(
NOTE: I'm using jQuery for it. But you can easily re-write it to work with pure javascript.
<html>
<head>
<title>Enter Key</title>
<script src="jquery-1.2.6.js"></script>
</head>
<body>
<div id="prompt" style="color:#eeffee;width:50px;height:50px;"></div>
<textarea id="txt" cols="25" rows="10"></textarea>
<script type="text/javascript">
$(document).ready(function(){
var ar=$("textarea").add($("input"));
var elems=new Array();
var key = 13;
$(ar).each(function(){
var i=$(this).attr("id");
if(i && i!=="")
elems.push(i);
});
elems.sort();
$().keypress(function(e){
var k=e.keycode || e.which;
var id = e.target.id;
if(k === key){
if(id){
var ar=$.grep(elems,function(a){ return a==id;});
if(ar.length === 0){
$("#prompt").html("Eating ");
return false;
}else{
$("#prompt").html("Allowed");
}
}else{
$("#prompt").html("Eating ");
return false;
}
}
});
});
</script>
</body>
</html>
You could achieve it by using Panel like below.
<asp:Panel runat="server" DefaultButton="">
other html/asp tags
</asp:Panel>
There should be other efficient ways.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx
Here is what I used to fix this problem.
<form runat="server" defaultbutton="DoNothing">
<asp:Button ID="DoNothing" runat="server" Enabled="false" style="display: none;" />
Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to handle this issue, is to disable the button immediately after the first click, however when I do this, it doesn't post.
I did do some research on this, god knows there's enough information, but other questions like Disable button on form submission, disabling the button appears to work. The original poster of Disable button after submit appears to have had the same problem as me, but there is no mention on how/if he resolved it.
Here's some code on how to repeat it (tested in IE8 Beta2, but had same problem in IE7)
My aspx code
<%# Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
function btn_onClick()
{
var chk = document.getElementById("chk");
if(chk.checked)
{
var btn = document.getElementById("btn");
btn.disabled = true;
}
}
</script>
<body>
<form id="form1" runat="server">
<asp:Literal ID="lit" Text="--:--:--" runat="server" />
<br />
<asp:Button ID="btn" Text="Submit" runat="server" />
<br />
<input type="checkbox" id="chk" />Disable button on first click
</form>
</body>
</html>
My cs code
using System;
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btn.Click += new EventHandler(btn_Click);
btn.OnClientClick = "btn_onClick();";
}
void btn_Click(object sender, EventArgs e)
{
lit.Text = DateTime.Now.ToString("HH:mm:ss");
}
}
Notice that when you click the button, a postback occurs, and the time is updated. But when you check the check box, the next time you click the button, the button is disabled (as expected), but never does the postback.
WHAT THE HECK AM I MISSING HERE???
Thanks in advance.
I think you're just missing this tag:
UseSubmitBehavior="false"
Try it like this:
<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" ValidationGroup="vgNew"/>
Explanation
UseSubmitBehavior="false" converts submit button to normal button (<input type="button">). If you don't want this to happen, you can hide submit button and immediately insert disabled button on its place. Because this happens so quickly it will look as button becoming disabled to user. Details are at the blog of Josh Stodola.
Code example (jQuery):
$("#<%= btnSubmit.ClientID %>").click(function()
{
$(this)
.hide()
.after('<input type="button" value="Please Wait..." disabled="disabled" />');
});
fallen888 is right, your approach doesn't work cross-browser. I use this little snippet to prevent double-click.
"Disabling" HTML controls doesn't always produce consistent behavior in all major browsers. So I try to stay away from doing that on the client-side, because (working with the ASP.NET model) you need to keep track of element's state on client and server in that case.
What I'd do is move button off the visible part of the window by switching the button's className to a CSS class that contains the following:
.hiddenButton
{
position: absolute;
top: -1000px;
left: -1000px;
}
Now, what to put in place of the button?
Either an image that looks like a disabled button
Or just plain text that says "Please wait..."
And this can be done the same way but in reverse. Start with the element being hidden at page load and then switch to a visible className on form submit.
We use the following JQuery script, to disable all buttons (input type=submit and button), when one button is clicked.
We just included the script in a global JavaScript file, so we don't have to do remember anything when creating new buttons.
$(document).ready(function() {
$(":button,:submit").bind("click", function() {
setTimeout(function() {
$(":button,:submit").attr("disabled", "true");
}, 0);
});
});
This script could easily be extended with a check for Page_ClientValidate().
document.getElementById('form1').onsubmit = function() {
document.getElementById('btn').disabled = true;
};
This is the correct and simple way to do this:
It works in all browsers (unlike the accepted solution above).
Create a helper method in your application (say in a Utlity Namespace):
Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
End Sub
Now from the code behind of each of your web pages you can simply call:
Utility.PreventMultipleClicks(button1, page)
where button1 is the the button you want to prevent multiple clicks.
What this does is simply sets the on click handler to: this.disabled=true
and then appends the buttons own post back handler, so we get:
onclick="this.disabled=true";__doPostBack('ID$ID','');"
This does not break the default behaviour of the page and works in all browsers as expected.
Enjoy!
FOR JQUERY USERS
You will get into all sorts of problems trying to add javascript directly to the onClick event on ASP.NET buttons when using jQuery event listeners.
I found the best way to disable buttons and get the postback to work was to do something like this:
$(buttonID).bind('click', function (e) {
if (ValidateForm(e)) {
//client side validation ok!
//disable the button:
$(buttonID).attr("disabled", true);
//force a postback:
try {
__doPostBack($(buttonID).attr("name"), "");
return true;
} catch (err) {
return true;
}
}
//client side validation failed!
return false;
});
Where ValidateForm is your custom validation function which returns true or false if your form validates client side.
And buttonID is the id of your button such as '#button1'
For debugging purposes, what happens if you put an else clause against the if(chk.checked)?
Make sure that your javascript function returns true (or a value that would evaluate to boolean true), otherwise the form won't get submitted.
function btn_click()
var chk = document.getElementById("chk");
if(chk.checked)
{
var btn = document.getElementById("btn");
btn.disabled = true;
return true; //this enables the controls action to propagate
}
else return false; //this prevents it from propagating
}
One can also try the following way to prevent double clicking of the "SUBMIT" Button:
.buttonload {
background-color: lightgrey; /* Grey background */
border: none; /* Remove borders */
color: black; /* Black text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
<!DOCTYPE html>
<html>
<head>
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script type="text/javascript">
$(function () {
SubmitButton = $("#btn");
SubmitButton.on("click", function () {
result = ValidateRecords();
if (result) {
$(this)
.hide()
.after('<button disabled class="buttonload"><i class= "fa fa-spinner fa-spin"></i>Processing Data...</button >');
}
});
});
function ValidateRecords() {
var DateTime = document.getElementById('lit').value;
if (!DateTime.trim()) {
return false;
}
else {
return true;
}
}
</script>
</body>
</html>
EXPLANATION(In Order of Code Appearance above):
CSS : Handles the spinner element used as part of the icon tag in the replaced button.
Adding the Icon Library in header is mandatory in case if you want to use the icon class fa-spinner.
In the script tag Validate method is called to check if all the mandatory form elements are filled prior clicking the submit button
Post the validation is successful, I am hiding the submit button[.hide()] and replacing with another button[.after()].
Setting the DISABLED property on the new button is mandatory or else it will work as an active button.
NOTE: I have used Button to replace the submit Button. But you can use input text or any other suitable element as per your requirements