I am bit struggling to understand how it works when you want to delete something using server side. I know how to use MessageBox but it is not ideal. I am advised to use popup on server side.
What I am trying to do is that when you click the button, popup should display to ask you if you are sure you want to delete it. If yes, delete it based on C# delete events. If no, cancel it. How to work with both of javascript and C#?
I got problem When I click the button, popup happens, and when i click yes, delete it which is working BUT when I click no, still delete it. How to handle with yes and no in C# or javascrpit? No idea how to do this.
Your excample code means alot to me. I need to understand. Thanks!!
Javascript
<script type='text/javascript'>
var result = confirm("Do you Want to Delete?");
if (result)
{
//do ajax call and delete from database
return true;
}
else
{
return false;
}
ASP.NET
<asp:Button runat="server" OnClick="btnDelete_Click" OnClientClick = " return confirm();" />
C#
protected void btnDelete_Click(object sender, EventArgs e)
{
//Delete operation
}
Html markup:
<asp:Button runat="server" OnClick="btnDelete_Click"
OnClientClick = " return myConfirm();" />
Js
<script type='text/javascript'>
function myConfirm(){
var result = confirm("Do you Want to Delete?");
if (result==true)
{
//do ajax call and delete from database
return true;
}
else
{
return false;
}
}
</script>
If you have a server button with both client and server events. You can check the client side, and decide weather the server side should be executed or not. for example :
add a CSS class to your button.
$('.CssClassOfYourButton').click(function (evt) {
if (condition)
return false;
// Post Back will not happen
}
if (confirm('Are you sure? \nDoing this will ......... .')) {
return true;
// if user clicks yes ,Post Back will happen and server side delete event is executed.
}
});
client side:
function confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you Want to Delete?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
return false;
}
document.forms[0].appendChild(confirm_value);
}
On server side:
protected void btnDelete_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
}
else
{
}
}
Related
I am using a confirmation window that will add a new value to database if the user clicks OK in the popup window. Also i have to verify a specific criteria before that. I have button and text box and the text box contains a required field validator. So if i click the button this validator fires first.
I will enter a number in this text box and press add, it will fetch a name value corresponding to this number from database and if name is found then it should ask a confirmation "Do you want to add this name?" and if name is not found then it should just popup a alert saying "name not found". If number value is less than 6 then it will show another popup saying "number not valid". I have done this as given below.
ASP.NET
<asp:TextBox ID="text_add" runat="server" MaxLength="6"></asp:TextBox>
<asp:RequiredFieldValidator ID="required_add_" ControlToValidate="text_add" ErrorMessage="Required" runat="server">Required</asp:RequiredFieldValidator>
<asp:Button ID="button_add" runat="server" Text="Add" OnClientClick="Confirm()" OnClick="button_add_Click" />
JavaScript
<script type = "text/javascript">
function Confirm() {
if (Page_ClientValidate()) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
</script>
C#
protected void button_add_Click(object sender, EventArgs e)
{
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//add the name
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
Here what happens is whenever i enter a number into text box and click the button, the Confirm() function is executed at first even if the number is less than 6 digits and in case i enter 6 digits and the name is not found in database same way the Confirm() function is executed. If i enter number less than 6 digits the confirm box comes first and after that the alert saying "number not valid" comes. How can i fire the confirm() function only if the conditions are met. I want to fire the confirm() function only if the button press event goes into the if (//name found) condition.
EDIT
I have removed the OnClientClick from the button and then changed the C# code to the following
protected void button_add_Click(object sender, EventArgs e)
{
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.AddData(sender, e);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
protected void AddData(object sender, EventArgs e)
{
// add data
}
I have made a seperte function to add data. I have added the ScriptManager to open confirm box and removed the OnClientClick in button. Now when i press the button the confirm box opens only if all conditions are satisfied. But when i press OK in confirm box nothing happens. The AddData function is not executed.
Change your confirm function to this:
function Confirm() {
if (Page_ClientValidate() &&
document.getElementById('text_add').value.length >5) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
else return false;
}
And change The
onClientClick=Confirm();
to this:
onClientClick= return Confirm()
to avoid submit under 6 length text.
You must have a hidden field between your post backs that shows it is in first post back or after confirmation:
<asp:HiddenField ID="isReadyForSave" runat="server" Value="false"/>
And change your code:
protected void button_add_Click(object sender, EventArgs e)
{
if(isReadyForSave.Value == "true" && Request.Form["confirm_value"] == "yes")
{
AddData();
isReadyForSave.Value = "false";
return;
}
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "confirm", "Confirm();", true);
isReadyForSave.Value = "true";
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
And change you javascript confirm() function to this:
function Confirm() {
if (Page_ClientValidate() &&
document.getElementById('text_add').value.length >5) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
return true;
}
else return false;
}
I've javascript confirmation function like this:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your team is incomplete. Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I want to show this when the team really incomplete. I check it in save button click. If false; I want to call JS confirm function:
if ((teamList.Contains("Purchasing") && teamList.Contains("Quality") && teamList.Contains("Process") && teamList.Contains("R&D")))
{ }
else
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CallMyFunction", "Confirm()", true);
}
If confirm returns yes, I want to save them. If no, I don't want to save them.
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Do save operations
}
These code snippets returns null first time, and it returns my confirm answer (yes or no) when the other button clicks.
How can I do?
I have a scenario where I want to check if user adds data with same date and same region again, it should give him a prompt alert.
I tried this with code behind,like below:-
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dtExcel = new DataTable();
dtExcel.Clear();
string StrCount = String.Empty;
string connString = "";
HttpPostedFile File = FileUpload1.PostedFile;
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
path = Server.MapPath(#"~/Excels/" + "/" + Filename.ToString());
File.SaveAs(path);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet 1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);
daExcel.Fill(dtExcel);
conn.Close();
DataTable DtMain = CF.ExecuteDT("select Tran_type, Order_Date, Region_Mkey from WMS_Future_Del_Order_Hdr where Tran_type = '" + CmbTypeOfAsn.SelectedValue + "' and Order_Date = convert(datetime,'" + TxtEdate.Value + "',103) and Region_Mkey = '" + ddlRegion.SelectedValue + "'"); // checks the duplicate records here
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
Also see my function for prompting the alert for duplicate message
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
but what happens here is even after cancel click, the excel file is uploaded and gets saved. I dont know why
Although Abbas Kapasi's solution based on AJAX is good one (and you do not want to/can not use the solution based on CheckBox as I suggested in my other post codebhind-javascript-alert-for-yes-and-no-not-working-exactly), if you are not familiar with AJAX or don't want to use AJAX then you may achieve it using following approach. It may seem a bit odd but you may modify it according to your requirements:
I am splitting the code to upload and find existing file/record in one procedure and the code to write/overwrite the records in another sub-procedure.
Then I am using two LinkButtons, LinkButtonLoad and LinkButtonOverwrite.
LinkButtonLoad will be attached to the call the main procedure which uploads and finds existing file/record. LinkButtonOverwrite will call the procedure to write/overwrite the records. LinkButtonOverwrite will remain hidden from the user.
In the first procedure if the system finds existing file/record it will show a client side prompt to the user to overwrite or not. If the file/record does not exist it will call second sub-procedure to write the records.
On client side, if the prompt is displayed for existing file/record and the user selects Cancel/No the process will not proceed. If the user selects OK/Yes then I'll be calling the procedure linked to the LinkButton2 to overwrite the records.
Now putting it all together:
In aspx/front end
<asp:LinkButton ID="LinkButtonLoad" runat="server" Text="Load Records" CssClass="button" ... />
<asp:LinkButton ID="LinkButtonOverwrite" runat="server" Text="ow" CssClass="button hidden" ... />
I'm using hidden CSS class to hide the button .hidden {display: none;}. Do NOT use visible="false" attribute, it'll not be available on the client side.
JavaScript on client side:
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
// get the action attribute of the hidden LinkButtonOverwrite here and call it on OK
// as an alternative you may also invoke the click event of this button
var defaultAction = $('#<%=LinkButtonOverwrite.ClientID %>').prop("href");
window.location.href = defaultAction;
}
else {
return false;
}
}
LinkButtonLoad in code behind:
protected void LinkButtonLoad_Click(object sender, EventArgs e)
{
//==============================================================
// YOUR CODE TO UPLOAD THE FILE, SAVE IT SO WE MAY USE IT AGAIN
//==============================================================
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
else
{
MySubToOverwrite();
}
}
LinkButtonOverwrite in code behind:
protected void LinkButtonOverwrite_Click(object sender, EventArgs e)
{
//===========================================================
// AS THE FILE IS ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
// YOU MAY ACCESS IT AND PERFORM REQUIRED OPERATIONS
//===========================================================
MySubToOverwrite();
}
MySubToOverwrite() code in behind:
private void MySubToOverwrite()
{
//==========================================================
// OVERWRITE YOUR RECORDS HERE
// FROM THE FILE ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
//==========================================================
}
Detecting duplicate records
There are a few ways you can do this. Just going to touch on the big picture here, in order of my personal preference:
Easiest method: Don't check. Prompt first. Provide a checkbox up front.
Use 2 Ajax requests: one to check for existing record, and another to save the file (if user said "OK" or if file not yet exists). Challenge: multiuser environments.
Multi-step POST back. Server code injects a dynamic control (or shows a hidden static one) that prompts user to overwrite. Ugly, but does not require JS. You may remember this from the '90s.
Versioning: more advanced, more complex, but for Enterprise systems this is the way to go. Do not overwrite files with same identifier; store a different version of it. Then you get a nice history and audit trail of who changed it. Makes it easy to go back to fix mistakes, blame people, etc.
Canceling the PostBack (if using option 3 or other postback method)
You need to bind to the correct button, and to prevent POST to the server (AKA "postback") you must return false in either
the click event handler of the rendered input type="button"
or
the submit event handler if the form
You can accomplish this by embedding the return value to myTestFunction() in the asp:Button itself:
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClientClick="if(!myTestFunction()){return false;}"
OnClick="btnSave_Click" />
<script>
function myTestFunction() {
return confirm('Override the file?');
}
</script>
use ajax function with webservice to check the same data and region
Submit button code
<asp:Button ID="btnupload" runat="server" OnClientClick="javascript return checkData()"
Text="Upload" OnClick="btnupload_Click"></asp:Button>
Javacript
<script>
function checkData() {
$.ajax({
type: "POST",
url: "demo.aspx/functionName1",
data: "{parameter1:'" + param1 "',parameter2:'" + param2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.d == 'Yes'){
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
else{
return true;
}
}
});
}
</script>
C# Code
using System.Web.Services; --- use this class
[WebMethod]
public static string functionName1(string parameter1, string parameter2)
{
------------------------------;
if(check Condition)
return "Yes";
else
return "No"
}
In reality, you just need the following to make it work. Use RegisterOnSubmitStatement instead of RegisterStartupScript. It would let you add script that executes in response to the button's onclick event. The script is executed before the button event is invoked, and gives you an opportunity to cancel the event.
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// You can place this in any method where you want to do the validation.
String scriptText =
"return confirm('Are you sure you want to override the file ?')";
ClientScript.RegisterOnSubmitStatement(this.GetType(),
"ConfirmSubmit", scriptText);
}
protected void btnSave_Click(object sender, EventArgs e)
{
}
Markup :
<asp:Button id="ConfirmSubmit" runat="server" OnClick="btnSave_Click"/>
I am trying to make a function actuated by a button click. On click, a function loops through each input type=text element, assigns their value attribute to variable, if that variable = null or variable = "" call method confirm('are you sure you want to save a blank row').
Here's my code/pseudo code:
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = $(this).attr('value');
var bool = false;
if(x == null || x == "")
{
bool = true;
}
else
{
send the request
}
if(bool == true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
send the request
}
else
{
do nothing or cancel the request
}
}
else
{
send the request
}
}
}
</script>
Here is my asp button code:
<asp:Button ID="btnSave" runat="server" Text="Save"/>
If you need more information, please let me know.
Thanks in advance
For ID issue, if you use ASP.Net 4.0 +, set ClientIDMode=Static
<asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save"/>
JS
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = this.value;
var bool = false;
if(x === null || x === "")
{
bool = true;
}
else
{
send the request
}
if(bool === true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
LoadData();
}
else
{
return;//do nothing
}
}
else
{
send the request
}
}
}
function LoadData()
{
$.ajax({
type: "GET",
url: 'page.aspx',
timeout: 1000,
success:function(data){
//do work
},
error:function(jqxhr, status){
if(status==="error"){
//handle error
}
});
}
</script>
Since it's ASP.NET, that ID is going to be rendered different, try grabbing the Client ID (if the JS is in the same file, if it is not, use a unique class and assign the handler via that)
$("#<%=btnSave.ClientID%>").click(function() {
$("input:text").each(function() {
if (!this.value.length) {
var confirm = confirm('are you sure you want to save a blank row')
..
}
});
});
You can also do like below....
<script type="text/javascript">
function isInputEmpty() {
var bool = false;
$("#btnSave").click(function () {
$('input[type=text]').each(function () {
var x = $(this).attr('value');
if (x == null || x == "") {
bool = true;
}
});
if (bool == true) {
if (confirm('Are you sure you want to save a blank URL?')) {
//send the request
}
else {
//do nothing or cancel the request
}
}
else {
//send the request
}
});
}
</script>
It's not entirely clear what your question is, but other answers here have rightfully focussed on the ID issue and .Net webforms changing the element's ID.
The other solutions suggested are fine, but there is also another way, and that is searching by partial ID. When clientIDmode isn't set to static (or if you're pre .Net 4.0) the .NET ID will always have the original id appended after an underscore, so you can find your element using jquery like this:
$("[id$='_btnSave']").click(function(){ ...
I have a button which needs get the confirm() value to do the database operation. For example: when clicking the button, a message popup to confirm "yes or no", if yes, it will do the deletion operation in database, if no, it will clear the textbox. How can I get the returned value from Javascript confirm() function. Please advise.
string jScript;
jScript = "<script> function processConfirm(answer) {if (answer) {return 'Facilitator Deleted';}else {return 'Cancelled';}} var confirmAnswer = confirm('You sure to delete ?');var theAnswer = processConfirm(confirmAnswer);alert(theAnswer);</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jScript);
/* SqlCommand cmd = new SqlCommand("TrainerFilter", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int, 50).Value = TextBox1.Text.Trim();
cmd.Parameters.Add("#result", SqlDbType.Int, 50).Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();*/
You can store the value of confirm_proceed() in an asp:HiddenField
You can modify your script as follows:
function confirm_proceed()
{
var hiddenField = document.getElementById('hiddenFieldId');
if (confirm("Are you sure you want to proceed?")==true)
{
hiddenField.value = 'true';
return true;
}
else
{
hiddenField.value = 'false';
return false;
}
}
This is a bit confusing, but assuming this confirm is tied to a button click, you would usually do something like this:
<script type="text/javascript">
processConfirm = function() {
var result = confirm("Are you sure you want to delete this?");
if (!result) {
alert("Cancelled"); //or set a label or whatever
return false; //cancel postback
}
return true; //perform postback
}
</script>
<asp:Button ID="Button1" runat="server" OnClientClick="return processConfirm();" OnClick="Button1_Click" />
And in the code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
//perform the delete logic since because if you reach here
//you know that the user confirmed
//throw up an alert when the page is reloaded confirming that the deletion
//you could also set a label here instead of an alert if you wanted
Page.ClientScript.RegisterStartupScript(this.GetType(), "confirmDelete", "alert('User was deleted');", true);
}