code behind confirm with custom validation - c#

i understand that we able to achieve this by using "onClientClick", but i want to check the validation first BEFORE the confirmation box.
javascript
function showConfirm() {
var result = window.confirm('Are you sure?');
if (result == true)
alert("ok");
}
html
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
C#
protected void Button1_Click(object sender, EventArgs e)
{
if(checkValidation() == true)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:showConfirm();", true);
//if(result == true) //how to get the result value?
//{
////run some code
//insert data into sql
//}
}
}
is there anyway i can get the confirmation result at code behind? without the if-else-statement, the data will insert into sql before user choose their decision.

i create a button with display:none
.hideButton{
display:none;
}
create code behind
protected void btnConfirm_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx");
}
trigger the btnConfirm click if user click Yes on confirmation box
$('#ContentPlaceHolder1_btnConfirm').trigger('click');

If you are doing a custom validation in Web forms that you much enable EnableClientScript="true" and write the JS validate function name in ClientValidationFunction="JSValidateFunctionName" like this you would be able to validate on client side before even going to server side.

Related

Fire Custom Validator Before Processing Other Code

I have the following in my .aspx file:
<asp:CustomValidator
ID="JobIDCustomFieldValidator"
runat="server"
ControlToValidate="JobID"
OnServerValidate="jobIDCustom_ServerValidate"
EnableClientScript="false"
SetFocusOnError="true"
Display="Dynamic"
ErrorMessage="! - Not Found"
CssClass="validationError">
</asp:CustomValidator>
<br />
<asp:TextBox ID="JobID" runat="server"></asp:TextBox>
<asp:Button runat="server" ID="ProcessButton" Text="Process" onclick="ProcessButton_Click" />
I have the following in my code behind file:
protected void ProcessButton_Click(object sender, EventArgs e)
{
Response.Write("I am in here");
}
protected void jobIDCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
// Impersonate a user for shared folder access.
using (UserImpersonation user = new UserImpersonation(properties.ShareUser, properties.Domain, properties.SharePassword))
{
e.IsValid = false;
// Check the user credentials.
if (user.ImpersonateValidUser())
{
e.IsValid = File.Exists(#"\\\\" + properties.RemoteServer + "\\" + properties.Share + "\\" + JobID.Text + ".dat");
}
}
}
I want the custom validator to be checked first and if it is false stop and do not run any of the code in the ProcessButton_Click() method. Is this possible? If not is there an alternative way I could set this up?
As far as I know I can't use client side validation with javascript to do the impersonating and file access.
Any help would be greatly appreciated.
To summarize check to see if the page is valid in the button click handler.
protected void ProcessButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do button stuff
}
}
"Validation controls test user input, set an error state, and produce error messages. They do not change the flow of page processing—for example, they do not bypass your code if they detect a user input error. Instead, you test the state of the controls in your code before performing application-specific logic. If you detect an error, you prevent your own code from running; the page continues to process and is returned to the user with error messages."
From MSDN
http://msdn.microsoft.com/en-us/library/dh9ad08f(v=vs.90).aspx

Client Interaction in WebForms

What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}

Getting the input of a confim box to C# variable in VS2005

How to get input from user using a confirm box in asp.net and store the input in a C# variable.
as whether it is a ok or cancel button. pls help me forward.
For Example i am using like this,
Response.Write("confirm('Testing FiileAlready existing Replace it?')");
instead i need the output of the confirm box in c# variable...
Try this:
Your javascript function:
<script type="text/javascript" language="javascript">
function ConfirmOnReplace() {
if (confirm("Are you sure?") == true)
return true;
else
return false;
}
</script>
The ASP.NET button:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return ConfirmOnReplace();" />
And the code-behind(YourPage.aspx.cs) file:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Click += new EventHandler(Button1_Click);
}
void Button1_Click(object sender, EventArgs e)
{
// If you are here, your javascript method returned true
// TODO: Replace the file, or do what you want
}
}

Confirmation message box in webapplication

Am using the below message box in asp.net web application. Now i want to convert this message box as a confirmation message box and do something when it is true else means reject the application.
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Are you sure, you want to apply?');</script>", false);
I think you are going about this the wrong way. You should display this confirmation before posting back, and then only post back if they choose to "Apply".
Using ASP.NET web controls, the Button control has an OnClientClick property which can be used to call javascript prior to Http POST:
You could do something like this:
<asp:button id="btn"
runat="server"
Text="Apply"
OnClientClick="return confirm('Are you sure you wish to apply?');"
OnClick="btn_Click" />
register script bellow instead of alert
<script type="text/javascript">
var r=confirm("Are you sure you are sure?")
if (r==true)
{
//You pressed OK!
}
else
{
//You pressed Cancel!
}
</script>
The javascript equivalent to a confirmation box is the confirm() method. This method returns a true or false value depending on the user's "OK" or "Cancel" button response.
Usage:
var confirmed = confirm('Are you sure?','Are you sure you want to delete this item?');
if(confirmed){
//do something
} else {
//do something else
}
Try this
Add this on your cs file to display a confirm instead of alert
string confirm =
"if(confirm('Are you surely want to do this ??')) __doPostBack('', 'confirmed');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", confirm, true);
Add this on same page to check when user is coming from that confirmation box
protected void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (string.Equals("confirmed",
parameter,
StringComparison.InvariantCultureIgnoreCase))
{
// Call your server side method here
}
}
For this I used __doPostBack you can learn more about it from here.
Hope it'll help you
private void showMessage(string msg){
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('"+ msg +"');</script>", false);
protected void BtnReg_Click(object sender, EventArgs e)
{
OracleHelper.OracleDBOpen();
object flag = OracleHelper.OracleExecuteScalar("your select Query ");
if (flag == null)
{
showMessage("Failed !!! ");
}
else
{
string reg = String.Format("your Insert Query ");
showMessage("successfuly");
OracleHelper.OracleExecuteNonQuery(reg);
}
OracleHelper.OracleDBClose();
}
}
To do this completely within C#, you can try this:
protected override void OnInit(EventArgs e)
{
AddConfirmationButton();
base.OnInit(e);
}
private void AddConfirmationButton()
{
Button confirmButton = new Button();
confirmButton.Text = "Action Foo";
string confirmationMessage = "Are you sure you wish to do action Foo?";
confirmButton.OnClientClick = "return confirm('" + confirmationMessage + "');";
confirmButton.Command += confirmButton_Command;
Controls.Add(confirmButton);
}
void confirmationMessage_Command(object sender, CommandEventArgs e)
{
DoActionFoo(); //work your magic here.
}
This presents and "OK/Cancel" dialog box to the user from the webpage. If the user clicks 'ok', the function from the command Event fires. If the user clicks 'cancel', nothing happens.
ScriptManager.RegisterStartupScript(page,this.GetType(), "temp","javascript:calopen();
",true);
function calopen()
{
if (confirm("Are you sure?"+'\n'+"Are you want to delete"))
{
enter code here
}
else
{
return false;
}
}
try this code check on OnClientClick event when user click on button
<script type="text/javascript">
function check()
{
var chk =confirm("Are you sure you are sure?")
if (chk==true)
{
// try you want
}
else
{
// try you do not want
}
return true;
}
</script>
<asp:button id="Button1"
runat="server"
Text="Button1"
OnClientClick="return check();"/>

How to show "success" message on submit?

Using C# with ASP.NET, how do I show a "success" message when my user submits a form? And at the same time say "The image has successfully saved", with a link, so that the image created can be viewed by clicking the link?
Wrap your form in an <asp:Panel> and create another <asp:Panel> with Visible="False" for your Thank you message. Once the form is submitted, change the visibility of each panel, setting the form to Visible="False", and the thank you message panel to Visible="True".
Hope that makes sense, here's an example:
<asp:Panel ID="pnlFormFields" runat="server">
... form fields here ...
</asp:Panel>
<asp:Panel ID="pnlThankYouMessage" runat="server" Visible="False">
... Thank you message here ...
</asp:Panel>
Then inside your codebehind
protected void btnSubmit_Click(object sender, EventArgs e) {
// Hook up uploaded image and assign link to it
pnlFormFields.Visible = false;
pnlThankYouMessage.Visible = true;
}
If you need label to display message. Add a label on the page and set its attribute visible = false in aspx and use the code below:
protected void btnSubmit_Click(object sender, EventArgs e) {
if(SaveRecordsToDataDatabase())
{
If(UploadImage())
{
showMessage("Save successfull",true);
}
else
{
showMessage("Save failed",false);
}
}
else
{
showMessage("Save failed",false);
}
}
private bool UploadImage()
{
// you upload image code..
}
private bool SaveRecordsToDatabase()
{
// db save code
}
private void showMessage(string message, bool success)
{
lblMsg.visible = true; // here lblMsg is asp label control on your aspx page.
lblMsg.FontBold = true;
if(success)
lblMsg.ForeColor = Color.Green;
else
lblMsg.ForeColor = Color.Green;
lblMsg.Text = message;
}
For consistency you can use Transaction in above code so as to prevent save operation if image upload fails. Otherwise its your choice. The new code with Transaction will be , given below:
protected void btnSubmit_Click(object sender, EventArgs e) {
using(TransactionScope scope = new TransactionScope())
{
if(SaveRecordsToDataDatabase())
{
If(UploadImage())
{
showMessage("Save successfull",true);
}
else
{
showMessage("Save failed",false);
}
}
else
{
showMessage("Save failed",false);
}
}
scope.complete()
}
Here to refer transaction scope, add reference System.Transactions.
İf you want to show message on client side controls, like alert("saccess");
you can use ajax and webmethod in Why doesn't my jQuery code work in Firefox and Chrome?
if you want to show message on server side you can use panel, label or div (runat server and have id) and default setting of them, set visiible false, when you show message you can set visible true via code behind..
use a label(visible=false) and a hyperlink from the toolbox .when u upload an image u must be inserting the url of savefile location to a database.so when that insert query is fired that will return an integer value which is d no of lines inserted in db.compare it like if that value > 0 then set visibily of label to true and label.text="success" finally set the navigate url of the hyperlink to d url of saved image which can be used to creat a view link of the image

Categories

Resources