Show a confirmation/dialogbox in asp.net(c#) - c#

Functionality I need to achieve is:
Confirmbutton_Click
Show a popup/dialogbox:
On click of Yes, I need to validate Email-Id and other personal details submitted.
If validation fails, show error messages and return false.
If email-id and other details are correct, then hide/show few Divs.
I had achieved this functionality in jQuery but now I am supposed to do it in server side. Firstly because the Divs were not showing up each time correctly and secondly due to security concern.
The suggestions I got on googling ask to write complete code (in script tag) at server side. That would be too much as I need to validate many fields.
Also, is there a way I can just do the validations at client side and come back to server side and show my Divs depending upon the validation result ? The client script will be executed before server side, so it is achievable.
I don't want to create a new popup page for this.
If anyone could help me with correct code or pointers to one, how to validate and show divs(showing div to be done from server side).
UPDATED:
I am midway, if anyone could help me any:
In page load(not post back) I hv added:
btnConfirm.Attributes.Add("onclick", "if(confirm('Confirm - Are you sure you want to go ahead.')) onConfirm(); else return false;");
In jQuery code i have added validations as:
function onConfirm() {
//Check if email-id is not blank, else show message and return to the page
if (isBlank($('#emailAddress').val()) == false) {
$('#errorBlankEmail').show();
return false;
}
}
//Text validation functions
function isBlank(valueSent) {
if ($.trim(valueSent) == "")
return false;
else
return true;
}
and the button code as:
<asp:Button ID="btnConfirm" runat="server" Text="Confirm" onclick="Confirm_Click" />
And the server side code for this:
protected void Confirm_Click(object sender, EventArgs e)
{
divConfirm.Visible = true;
}
Now when I click on button, it works until I validate and validation fails, it executes the server side code. Is there a way where I can avoid the server-side code if result is false in client click code ?

You may want to try using http://www.telerik.com/ ASP.net AJAX controls, or Ajax Control Toolkit Modal Extender. Ive used both and they are exactly what your after.

I woudn't suggest to do it this way , but maybe this will point you to better solution.
From server side as you mentioned you can use static function
var script = #"<script> $("#somediv").dialog() </script>", false);
ClientScript.RegisterClientScriptBlock(GetType(), "some", , false);
(#somediv) is encaplulated with user control and contains all validation logic.
The problem is server validation of your div , since after postback on div ( on server side validation) your div will be closed , and again you need to pup it up from server ,
This approach will mess up things ... I'd use new popup window that will return result.

you won't get a confirmation on the server. the server has not concept of user interaction within the request/response. it can only receive the request, process it, and send a response.
what you can do is send a request to generate a response which will ask for the user to confirm. the user would then click "yes" which will create another request. the server will receive the request, process the request and send a response.
but what you cannot do is ask the user to confirm the request while processing it on the server. that confirmation must have already been done.
you can validate the request the request on the server, but that is just standard validation. nothing fancy to do there.

you can use jQuery ui Dialog - Modal Confirmation
and on confirm use __doPostback to fire the event 'Confirmbutton_Click'
It is just another way, but it won't be as easy as telerik controls..
<script>
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Confirm": function() {
$( this ).dialog( "close" );
__doPostBack('#<%= Confirmbutton.UniqueID %>', null)
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
And as html,
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<asp:button id="Confirmbutton" runat="Server" OnClick="Confirmbutton_Click" style="display:none;" />

Related

OnClientClick custom message box before Onclick event handler not working

I wanted to have a Custom Message Box OnClientClick . If the User Selects Yes then the Onclick Event handler in the C# code should get trigger. But somehow i am not able to do this using ASP.net and jquery.
As of now what is happening
Only C# code is triggered
What i was expecting
ClientSide Confirmation message (If User Clicks "YES" ) Then Server-side
code triggers.
My HTML
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
OnClientClick="if(!ShowDeleteFormConfirmation()) {return false;};" />
</div>
</form>
Jquery
function ShowDeleteFormConfirmation() {
var confirmationMessage,
dlgButtons = {
"No": function () {
$(this).dialog("close");
return false;
},
"Yes": function () {
$(this).dialog("close");
return true;
}
};
confirmationMessage = "This form has already been assigned and will be marked as deleted.";
var $panelContainer = $("<div>" + confirmationMessage + "</div>").appendTo('body');
$panelContainer.attr("title", "Confirmation to delete a form");
var myPos = [$(window).width() / 2 - 100, 50];
$panelContainer.dialog({
modal: false,
draggable: false,
position: myPos,
button: dlgButtons
});
}
C# ////OnClick
protected void btnDelete_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Delete button clicked.');", true);
} ```
This is what i wanted to implement.
http://jsfiddle.net/y5z01nbr/
Thanks for having a look.
Ok, while your code would work if you used "confirm" in the js code, that's because alert() and confirm() HALTS the calling code.
However, today, near ALL WEB code libraries are written to NOT halt, and NOT freeze up the browser. And jQuery is one such system. (it does not HALT the code). While I could introduce the concepts of await - that's becoming a wee bit too complex for this POST.
So, what this means:
the jQuery code does NOT halt,
and thus when you click on the button,
the client side code runs WITHOUT halting
and thus the button click (server side code) will
ALSO run right away - not waiting.
So, in the case of a jQuery dialog? You can't HALT the code. this means you have to flip this backwards. The jQuery dialog is to be displayed, AND THEN you have to call/run/click on that server side button. So, you have to add a new button, and use style="display:none" ot the existing button. Then display the dialog, and based on the answer you THEN click on (call) that origional button you have/had now.
The code will thus look like this:
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
Style="display:none" clientIDmode="static" />
<asp:Button ID="btnSubmitX" Text="submit" runat="server"
clientIDmode="static" OnClientClick="ShowDeleteFormConfirmation();" />
<\div>
So I dropped in another button - no server behind code. Hide first button with display none, and removed the client click. I moved the client click to 2nd button.
Now, we can do this:
dlgButtons = {
"No": function () {
$(this).dialog("close");
},
"Yes": function () {
$(this).dialog("close");
$('#btnSubmit').click();
}
};
So what we do is launch the dialog. And based on yes, then we click our button. If you choose no, then the dialog is dismissed, but no other action need take place.
A a GENERAL hard and fast rule?
Your browser code is RARE these days blocking code - calling a jQuery.ui dialog and in fact most of these newer UI controls? The code does NOT wait, does NOT halt. And this means you can't use the return true/false to control if the server side event stub will run or not (you can use js confirm(), but not jQuery, since it don't wait, nor halt the code).

Confirm box in asp.net web form application

I want to give user warning with confirm message box if they want to save without uploading image.
Code fires when user click on save button
if (string.IsNullOrEmpty(obj.Image)) {
obj.Image= null;
//Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "alert('Please Upload Image!');", true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "confirm('Are you sure you want to save without uploading images?');", true);
}
Above logic for was for showing confirm box but it doesn't show.
Besides that, how can I trap if user clicked on Yes or No button?
so that i can fire related code accordingly.
Update:
I am able to show confirm box with following code
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "confirm('Are you sure?');", true);
But i am not sure how i am going to trap the YES or No event
To handle the result of a confirm popup box - check the return value.
If OK is clicked it will return true, else it will return false.
EG:
if(confirm('test')) {
alert('ok clicked')
} else {
alert('cancel clicked or closed popup')
}
JSFiddle example code in action
EDIT: comments
To resubmit the form if the user clicks OK on the confirm dialog something like this is what you need:
Codebehind:
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"msgbxConfirm",
"doConfirm();",
true
);
aspx page:
<script type=text/javascript>
function doConfirm() {
if(confirm('Are you sure?') {
document.getElementById(<id_of_form_submit_button>).click();
}
}
</script>
One thing i am adding here, you can not get the confirm result in server side code, you have to write that code in JS side. So to maintain it in better manner, you can use following JS in aspx.
function ConfirmAndExecute()
{
if(confirm("Are you sure?"))
{
OnConfirm();
}
else
alert("you missed !")
}
function OnConfirm()
{
// JS Code to handle post confirm operation
}
And in server side, page_load, use following.
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "ConfirmAndExecute();", true);
You could also just add an onclick client script event handle to prevent submission of the form unless the confirmation is true so you don't have to deal with the script registration. Just add the code below into your asp:button definition
<asp:Button id="btnSave" Text="Save" runat="server" OnClientClick="return confirm('Are you sure?');" />

Update UI from code behind in real time

I've created a socket listener, and I need to display a div (keep it hidden, then make it visible), when the server detects a certain socket data.
I've tried to use a thread, but it doesn't update the UI in realtime, only if the page is reloaded or if you do a post back.
Here is an example of what I want to do, in this case I only want to update a textbox with codebehind data, I would like to do it without ajax, javascript or jQuery, if possible.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
Thread t = new Thread(TestThread);
t.Start();
}
private void TestThread()
{
for (int i = 0; i <= 1000000000; i++)
{
myTextbox.Text += "1";
}
}
Webpage:
<asp:UpdatePanel runat="server" ID="myPanel" >
<ContentTemplate>
<asp:TextBox runat="server" ID="myTextbox" />
</ContentTemplate>
</asp:UpdatePanel>
what you are trying to do is change the UI (modify client components) from server code (code behind) in asp.net when the server already sent the data to the client.
you have to use client side scripting/coding.
As far as I know, this is not possible without using ajax or JavaScript.
ASP.NET is only responsible for generating the html that is sent from your web-server to the client. Once that html is rendered in the browser, the only way to update the html is via JavaScript.
You can do a Partial Render in WebForms using their AJAX handler without having to write jQuery by enabling a partialRenderingEnabled attribute in the ScriptManager tag. There's no way to do this without scripting or AJAX, the content has to get back to the server to run your code-behind somehow, but at least this way you don't have to write any JavaScript yourself.
For real-time web functionality check out :
SignalR
In a web enviornment, there is no way for the server side to reach out for the client except in the request-response scenario, where the client has to send a request to the server side, the server side handles the request and replies with a response.
EDIT :
SignalR uses the best available technique, websockets when available, if not, AJAX long polling technique in which the client polls(sends a request) to the server, and the server replies only when a certain change to the observed data happens, else SignalR tries repetitve AJAX requests, polling the server over and over until the server replies with the change on the observed data (Worst scenario !).
Also, HTML 5 contains web-sockets, i don't have enough information about it, but it maybe interesting to check out.
With minimal JavaScript you could utilise Server Sent Events for simplex data (from server to client) It doesn't have the overhead of Websockets which has a bit of cost in terms of establishing a connection. However I don't think all browsers are supported but there might be polyfill available for it (library to provide functionality in absence of native support)
Checkout:
http://www.html5rocks.com/en/tutorials/eventsource/basics/
In ASP.NET Threads gets aborted as soon as the page unloads, so this is not possibler you way, sorry.
Your approach could be using AJAX to poll the status from the server on regular intervals. Server on the other hand, will reply according to change in data.
in your ASP.NET Page, add the following script
<head>
<script type="text/javascript" language="javascript">
function poll()
{
var ajax;
if(window.XMLHttpRequest)
ajax = new XMLHttpRequest();
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");
url = "yourPageOrHandler.aspx";
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
// success
var receivedText = ajax.responseText;
}
else
{
// error, do the needful
}
}
ajax.open("GET", url, true);
ajax.send();
setTimeout("poll()", 1000); //polls every 1 second, you can change the duration here.
}
</script>
</head>
Start the polling before page finishes
<body>
.
.
.
.
<script type="text/javascript" language="javascript">
poll();
</script>
</body>
Alternatively, you can use the ASP.NET AJAX controls, but that will be heavier compared to JavaScript AJAX.
Glad to help! Please remember to accept the answer if you found it helpful.

How to call javascript method in asp.net web application

I want to use a javascript function inside a c# function
protected void button1_Click(object sender,EventArgs e){
//javascript function call ex.
/*
boolean b=the return of:
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {return true;}
else {
return false;
}
}
</script>
*/
}
how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?
If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.
string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.
You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.
In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.
I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.
If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Do you want to delimit the record?');" />
If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.
You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.
If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.

Preventing Over Posting in ASP.NET Webforms

I know this is a basic question, but I am curious as to what the different options are, and what the best practice would be.
If I have a form that is responsible for saving reservations into a system, how can I prevent the form from being posted twice if the user hits the button twice really quickly?
I know there are a few ways in which I can accomplish this, but I am not quite sure which is the standard way of preventing this. Partially because I am new to web forms, and am used to dealing with MVC.
Thanks ahead of time.
I've used two approaches to this problem:
Use a token based approach. Each page has a hidden input with the current random token. This token is also stored in the user's session. Once the postback occurrs, I compare tokens and, if they are valid, generate a new session token and continue processing. When the second postback occurs, the token no longer matches and prevents processing.
Use javascript to disable the submit button. If you take this approach, and need the button event handler to fire, you'll need to create a hidden input with the name attribute of the button before submitting. The hidden input is required because disabled inputs do not end up in the post data.
I would recommend a client-side onClick event handler that disables the button or makes it invisible, preferably the latter, and replace the button with a label that reads "Processing..." or something like this
I have been using something like this when using an asp:Button for submitting:
1) Set the submit button's UseSubmitBehavior="false"
2) Set the submit button's OnClientClick="pleaseWait(this, 'Please Wait...');"
3) Include javascript code in the page:
function pleaseWait(obj, message) {
if (typeof(Page_ClientValidate) == 'function') {
if (Page_ClientValidate()) {
obj.disabled = true;
obj.value = message;
return true;
}
}
return false;
}
This solution is nice because it is simple but still accounts for client-side javascript validations. It isn't perfect, because it still relies on Javascript, which could be turned off, but that's unlikely to be done by someone who doesn't have the sense to click once and wait for a response. :)
Easy way - use the ajax AnimationExtender control.http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Animation/Animation.aspx
Simply attach the extender to the button and add a disable action.
<asp:Button ID="CopyScenarioButton" ClientIDMode="Static" OnClick="CopyScenarioButton_Click"
OnClientClick="setTimeout( function() {$('#CopyScenarioButton').attr('disabled', 'disabled');},0)"
EnableViewState="false" Text="Save New Scenario" ToolTip="Save New Scenario"
CssClass="btnNormal" runat="server" />
or the later version that includes some validation first:
function PreSaveHybrid() {
var doSave = PreSave();
if (doSave !== false) //returns nothing if it's not a cancel
setTimeout(function () { $('#btnSave').attr('disabled', 'disabled'); }, 0);
return doSave;
}

Categories

Resources