Fire Custom Validator Before Processing Other Code - c#

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

Related

Why doesn't asp.net button work?

I have used this behind asp button click function. It works on local system but not after begin deployed on server. Why ?
public void EmployeeDeActivation()
{
hdnfieldSessionPersonalInfoID.Value = "0";
Session["ExtraPersonalInfoID"] = 0;
Response.Redirect("EmployeeInformation.aspx", false);
}
.aspx code:
<asp:Button ID="btnEmployeeActivated" runat="server" Visible="false" OnClick="btnEmployeeActivated_Click"
CssClass="btn btn-rounded pull-right btnEmployeeActivated" />
i.e. when i click button when on local system, it hits then button event and refrehes the page but when it doesn't work like then button click never hits.
Update:
protected void btnEmployeeActivated_Click(object sender, EventArgs e)
{
try
{
EmployeeDeActivation();
}
catch (Exception ex)
{
throw;
}
}
Doesn't this method need to accept an event handler? E.g.
protected virtual void OnClick(
EventArgs e
)
Also, the part of code where you set your hidden is not needed as you redirect after.
Also it has the wrong name as it doesn't match the onclick name
Try to enable Trace and log on every method in the page. Try to visualize what your code is doing during postback.
Another useful tool is Glimpse.
Hope it helps!
asp button property "Visible" is set to false in your code. how come button is rendering at first place ?

asp Custom Validator fires too late

I have a form with a custom validator for the date:
<asp:CustomValidator runat="server" ID="cusCustom"
ControlToValidate="fdate"
Display="None"
OnServerValidate="customdate"
ErrorMessage="You need to book 24 hours earlier" />
<ajaxToolkit:ValidatorCalloutExtender
ID="ValidatorCalloutExtender4"
TargetControlId="cusCustom" runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
And the function behind:
protected void customdate(object sender, ServerValidateEventArgs e)
{
string dateString = String.Format("{0} {1}:{2}:00", fdate.Text, TimeSelector1.Hour, TimeSelector1.Minute);
DateTime selectedDateTime = new DateTime();
if (DateTime.TryParse(dateString, out selectedDateTime))
{
if (selectedDateTime > DateTime.Now.AddHours(24))
{
e.IsValid = true;
} else {
e.IsValid = false;
}
}
}
The problem is that it works fine, it detects what it needs to detect and it triggers the warning, but... it triggers it too late! If I enter a wrong date in the form, I am able to submit it, and I will find the warning about this bad validation next time I open the modalpopup with the form to enter a new booking.
All the other validators I have in the same form work fine. This is the button that launches the form:
<asp:Button ID="btnNew" runat="server" Text="New" CausesValidation="false" />
It has the CausesValidation set to false, and that works very well for the normal validators. Is only the custom one that runs too late...
Any suggestions?
You should probably have your popup firing an event to check whether the input is valid after you close it. I'll provide you with some pseudo-code.
<popupModalBox OnClose="PopupModal_OnClose" />
Triggering a method on the server
void PopupModal_OnClose(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Do something
}
else
{
// Do something else
}
}

code behind confirm with custom validation

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.

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
}

On ASP.NET form submit it throws an Object reference not set to an instance of an object.

I have a simple email form written in ASP.NET with the logic in the codebehind file. It's all in C# (the logic that is...). Anyways, on page load I have the following:
protected void Page_Load(object sender, EventArgs e)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
This works great as it pulls the users information into a few fields so they don't have to fill everything out by hand.
My other 2 methods in the code behind:
protected void SubmitForm_Click(object sender, EventArgs e)
{
SendEmail();
}
protected void SendEmail()
{
try
{
//compose email and send
}
catch (Exception ex)
{
ErrorMessage.Text = "Error: " + ex.ToString();
}
}
On my form page the button code is this:
<center>
<asp:Button runat="server" Text="Submit" ID="Submit" OnClick="SubmitForm_Click" class="button red" />
</center>
The error occurs when I click the send button on the form that generates the email and sends it. I can remove the Page_Load code and works great but I'd like to keep it there so the user doesn't have to fill out as much information.
I've used my Google Fu and read a ton of threads/articles but can't seem to find the solution...
Thanks for any assistance.
Add check for IsPostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
}
Have you tried adding if (Page.IsPostBack == false) to your Page_Load event?
I assume that the Request.Form code comes from fields that the user has filled out, but without seeing the rest of your markup, I'm not sure why you'd have to re-assign values from the form to what appear to be other fields on the form.
Where specifically is the error occurring?
From your code, I'm assuming that you are posting to your email form from another page and passing the parameters across.
If that's the case then assuming your .Text are the page controls then you should look at containing the control fillers in an If(!IsPostback) {...} for the first loading of the page only. Then your email code can read from the local controls.
My guess is that the "Request.Form[..." items are probably the ones kicking back error on postback.
HTH
Dave

Categories

Resources