Popup message box in c# - asp.net

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

Related

How to hide custom control after certain time

I have a custom control which displays results of some operations.
It is hidden by default and its made visible on the code-behind of some other class.
Now I want to hide it after a certain amount of time. How do I do it?
Edit:
Some answers suggested adding following javascript block at the end of the custom control which is not working if Visible="false" is used on the custom control.
But I did not made that clear enough and so accepted that as an answer.
Have to take a look at: How to call javascript function from code-behind
The timeout function is correctly called if Visible="true" is used.
ASPX:
<control id="customControl" runat="server" Visible="false"/>
Solution if Visible="true" is used in markup:
Custom control - ASPX:
<div id="body">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function() { document.getElementById('<%=Me.divBody.ClientID%>').style.display = 'none'; }, 2000);
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Solution if Visible="false" is used in markup:
From start the script block is not rendered and later is not added automatically. So we need to register it.
Custom control - ASPX:
<div id="divBody">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function(){ alert("test"); });
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Dim hideScript AS String = "window.setTimeout(function() { document.getElementById('" & Me.divBody.ClientID & "').style.display = 'none'; }, 2000);"
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.GetType, "script", hideScript, True)
Source: http://www.codeproject.com/Tips/85960/ASP-NET-Hide-Controls-after-number-of-seconds
I haven't seen any reference to jQuery in the question, hence vanilla JS solution:
Put this at the end of the User Control file
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%=this.ClientID%>").style.display = "none";
}, 5000);
</script>
You could have a property on the object which when executed changed the visible property to false if you were outside of a stipulated time frame, so you'd have a visible from and until field and have that generate a boolean when compared to the current time.
You can probably use the javascript setTimeout function to execute some code to hide the div which has the user control to hide after a time period
<div id="divUserControlContainer">
//put your user control embed code here
</div>
<script type="text/javascript">
$(function(){
window.setTimeout(function() {
$("#divUserControlContainer").hide();
}, 2000);
});
</script>
You achieve it by simple JQuery methods:
$("#CustomControl").hide(1000);
$("#CustomControl").show();

ClientScript.RegisterClientScriptBlock not working

I have a popup in my page which I am trying to show on dropdownlist selected index changed event.
Here is register statement
ClientScript.RegisterClientScriptBlock(GetType(),"id", "ShowApplicationPopUp()",true);
Here is my javascript function
function ShowApplicationPopUp() {
$('#NewCustomerMask').show("slow");
$('#NewCustomerApplicationPopUp').show("slow");
}
Both of my divs are initially hidden by using display:none; statement.
The problem is when my dropdownlist is changed the popup is not seen at all.I tried putting an alert statement to check if the function is called , and the alert statement is fired.Any ideas as to what I am doing wrong.
Any suggestions are welcome.
Thanks.
When you use RegisterClientScriptBlock the Javascript code is inserted early in the page, so it will run before the elements are loaded.
Use RegisterStartupScript instead, which places the code at the end of the form.
I too could not get this code to work but thanks to the above I now have working code. Note, I have a linkbutton inside an Ajax Update Panel.
in my code behind aspx.cs page is:
protected void OpenButton_Click(object s, EventArgs e)
{
// open new window
string httpLink = "../newWindow.aspx";
ScriptManager.RegisterStartupScript(this, GetType(), "script", "openWindow('" + httpLink + "');", true);
}
in my apsx page is first the link to jQuery source, then second the JavaScript for the openWindow function:
<script src="../js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
function openWindow(url) {
var w = window.open(url, '', 'width=1000,height=1000,toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
w.focus();
}
</script>
and the link that makes it all happen:
<asp:LinkButton Text="Open New Window" ID="LnkBtn" OnClick="OpenButton_Click" runat="server" EnableViewState="False" BorderStyle="None"></asp:LinkButton>
Im not a jQuery expert and must attribute some of this to the following blog:
https://blog.yaplex.com/asp-net/open-new-window-from-code-behind-in-asp-net/

ASP.NET how to call a button web control's OnClientClick event from code-behind (server-side)

Using ASP.NET 4.0 (c#), I want to call a button's OnClientClick event from code-behind (server-side). How do I code that in the code-behind file so that when the page is rendered again, the OnClientClick event is fired like the user clicked the button?
Here are two ways to "call" the javascript alert function from code behind. You may be able to replace the alert function with your function:
public static void ShowAlert(Page page, String message)
{
String Output;
Output = String.Format("alert('{0}');",message);
page.ClientScript.RegisterStartupScript(page.GetType(), "Key", Output, true);
}
public static void ShowAlert(HttpResponse response, String message)
{
String Output;
Output = String.Format("<Script Language='javascript'> alert('{0}');</script>", message);
response.Write(Output);
}
Add a little JQuery to the page...
<head>
<!-- Add the jquery library to your page -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<!-- Document.ready runs when the page is loaded -->
<script type="text/javascript">
$(document).ready(function () {
$('#MyButtonID').click(); // Find the button and click it.
});
</script>
</head>

Disable buttons on post back using jquery in .net app

I have a asp.net app that I want to disable the buttons as soon as they are clicked in order to prevent multiple submissions. I'd like to use jquery for this as the site already liberally uses it anyway.
What I've tried is:
$(document).ready(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
})
});
The above will disable the button, and the page submits, but the asp.net button on click handler is never called. Simply removing the above and the buttons work as normal.
Is there a better way? Or, rather, what am I doing wrong?
UPDATE
Okay, I finally had a little time to put a very simple page together.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SubTest.aspx.cs" Inherits="MyTesting.SubTest" %>
<!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">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button 2" />
</div>
</form>
</body>
</html>
The code behind looks like:
using System;
namespace MyTesting {
public partial class SubTest : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// this will execute when any button is pressed
Response.Write("postback");
}
}
protected void Button1_Click(object sender, EventArgs e) {
// never executes
System.Threading.Thread.Sleep(1000);
Response.Write("Button 1 clicked<br />");
} // method::Button1_Click
protected void Button2_Click(object sender, EventArgs e) {
// never executes
System.Threading.Thread.Sleep(1000);
Response.Write("Button 2 clicked<br />");
} // method::Button2_Click
}
}
When you click on a button it obviously disables the buttons, but NEITHER of the button clicks are run.
Rendered HTML
<!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">
<head><title>
</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<form name="form1" method="post" action="SubTest.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTcxODU4OTc0MWRkParC5rVFUblFs8AkhNMEtFAWlU4=" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKB57WhCAKM54rGBgK7q7GGCC6LlWKFoij9FIBVuI0HOVju/fTy" />
</div>
<div>
<input type="submit" name="Button1" value="Button" id="Button1" />
<input type="submit" name="Button2" value="Button 2" id="Button2" />
</div>
</form>
</body>
</html>
You can do it a slightly different way, like this:
$(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]').click(function() { return false; });
});
});
What this does is makes future clicks ineffective, basically making them do nothing. When you disable an input, it also removes the key/value pair from being submitted with the <form>, so your server-side action which is triggered by it doesn't work.
It's worth noting, in jQuery 1.4.3 you'll be able to shorten this down to:
$(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]').click(false);
});
});
The approach of disabling the button before the submit has two effects: -
a) The button takes on the disabled appearance.
b) The button's value is not posted in the form parameters.
If the button's value is not being posted to the server, ASP.Net does not know which button was pressed and thus it does not run the relevent OnClick handler.
To verify add the following to your code behind
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Load " + IsPostBack + "<br />");
foreach (string s in Request.Form.AllKeys)
{
Response.Write(string.Format("s:'{0}' = {1}<br />", s, Request.Form[s]));
}
}
And then run the page (both with J.S. to disable the buttons and without).
If the button's value is not being posted to the server, ASP.Net does not know which button was pressed and thus it does not run the relevent OnClick handler.
Just another observation. Alternatively, you can lock UI with a nice overlay busy message.
The Mark-up part:
$(function() { // when document has loaded
($.unblockUI); //unlock UI
//Show busy message on click event and disable UI
$('#btnHelloWorld').click(function() {
$.blockUI({ message: '<h4><img src="busy.gif" />Please wait...</h4>' });
});
});
<asp:Button ID="btnHelloWorld" runat="server" Text="Hello World" /><br/>
The Code behind:
Protected Sub btnHelloWorld_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHelloWorld.Click
Label1.Text = "Hello World"
Threading.Thread.Sleep(5000)
End Sub
Check out jQuery BlockUI Plugin
I just wanted to add an additional resolution. We decided to just completely remove the button once it was clicked and replace it with some text.
To do this we did:
$(function () {
$(".DisableButton").click(function () {
$(this).hide();
$(this).after('<p>Please Wait. Retrieving information. This may take up to 60 seconds.</p>');
});
});
Note that this hides the button then injects some html after the buttons code. Hiding it allows .Net to go ahead and run the onclick handler during post back while removing it as a clickable thing on the screen.
Add this attribute to your button:
usesubmitbehavior="False"
This will insert something like the following into onclick:
javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$Main$Tabs$SaveTab$Cancel", "", true, "", "", false, false))
This code will cause a post back even if the button is disabled. Showing a confirmation dialog and allowing the post back to be cancelled gets a little more interesting:
var click = $("[id$='_Cancel']")[0].onclick;
$("[id$='_Cancel']")[0].onclick = null;
$("[id$='_Cancel']").bind('click', function (event) { addFeeSchedule.onCancelClick(event) });
$("[id$='_Cancel']").bind('click', click);
In order to prevent the post back from occurring immediately, remove the onclick code inserted by .net and bind it after your own function using jQuery. Use event.stopImmediatePropagation(), to prevent the post back:
onCancelClick: function (event) {
var confirmResponse;
confirmResponse = confirm('No fee schedule will be created.\n\nAre you sure you want to cancel?');
if (confirmResponse == true) {
showWait();
event.target.disabled = 'true';
} else {
event.stopImmediatePropagation();
}
},
The answer provided by Nick Craver is by far the best solution that I've found anywhere on the net. There is one situation, however, where the solution does not work well - when the form contains submit buttons within an UpdatePanel with it's UpdateMode property set to "Conditional" and/or ChildrenAsTriggers property set to false.
In these situations, the contents of the update panels are not automatically refreshed when the async postback has completed. So if these update panels contained any submit buttons then the given solution would effectively leave these buttons permanently disabled.
The following enhancement to the solution handles this problem by re-enabling the buttons after an async, or 'partial', postback:
var canProcessClicks = true;
if (typeof (Sys) != 'undefined') {
// handle partial-postback
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager .add_initializeRequest(function() {
// postback started
canProcessClicks = false;
});
requestManager .add_endRequest(function() {
// postback completed
canProcessClicks = true;
});
}
$(function () {
$('input[type=submit]').on("click", function () {
return canProcessClicks ;
});
$("#aspnetForm").submit(function () {
if (typeof (Sys) != 'undefined' && Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
// this is an async postback so ignore because this is already handled
} else {
// full postback started
canProcessClicks = false;
}
});
});
For this you have to use input button attribute disable all the controls
<script language="javascript" type="text/javascript">
function MyDisableFunction() {
alert(`Now You Postback Start`);
$(":input").attr("disabled", true);
return true;
}
</script>
Fore more detail check this link

How to show a message box in an ASP.NET page?

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....

Resources