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
}
Related
I'm using web forms
Right now my code runs when I leave the text box and the text has changed. I am running into issues. If I change the text but hit a button instead of enter, it resets via code. I need to be able to change the text and click a button which wont yet do anything, or change the text and hit enter which will trigger code.
thanks for the help
This is text changed event for the text box with notations of what im needing to do. really what I think I need is an event for clicking enter, not changing text
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
}
You need to implement a method for the KeyDown event of your textbox.
private void txtboxPlate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
//Code
}
}
Keydown is a client-side event, as far as I know you're more than likely going to have to use JavaScript/Jquery.
Refer to the following link:
Textbox Keydown Event
I would of used a comment but... rep issues :/
edit:
To anyone that hasn't realised yet, the question changed to webforms not winforms
Alternative:
Use a button.
You could place a button next to the textfield, it's simple and not a lot of work goes into it. You can set the TabIndex of the textbox to 1 and the TabIndex of the button to 2 so when you hit TAB it will focus the textbox and if pressed again it will focus the button. You could also look into adding the button to the textbox for design purposes.
edit: You also need to think about post back, when you hit a button the page get's post back meaning values are lost, to persist the data within the field you would have to use view state, session variables or a hidden field. For simplicity I'd set the value of the text box to a hidden field and then simply re-apply the value on page_load. If the value needs to persist across multiple postbacks/accessed from other pages use session variables.
So as a code example:
Remove the Text_changed event entirely.
protected void btnDoStuff(object sender, EventArgs e)
{
if(txtPlateNumber.Text == "Plate Number")
{
//Do stuff
}
else
{
//Do other stuff
}
}
-
If you notice the value disappearing after the post back do something like:
protected void btnDoStuff(object sender, EventArgs e)
{
if(txtPlateNumber.Text == "Plate Number")
{
//Do stuff
myHiddenField.Value == txtPlateNumber.Text;
}
else
{
//Do other stuff
}
}
then reset the value on page_load.
If this is winform and you still want to use textchanged you can try catching your code first for example:
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
//Catching code
if (txtboxPlate.Text != "")
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
cause what textchanged is doing is unless txtboxPlate.Text equels "plate number" it will always do the else statement. Correct me if i'm wrong though but i had the same problem before which almost made me go insane.
Or try above 1 upvote code:
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
//Event only happens if you press enter
if (e.KeyCode == Keys.Enter)
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
}
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 ?
In my button click, I would like to cause the page validation to fail if it meets a certain criteria. The problem is that that Page.IsValid is read-only.
This is what I am trying in my button click:
protected override void CreateChildControls()
{
base.CreateChildControls(container);
MyBtn += MyBtn_Click;
MyBtn += MyBtn_Click2; // Cannot move this
}
protected void MyBtn_Click(object sender, System.EventArgs e)
{
CaptchaControl.Validate();
if (!CaptchaControl.IsValid)
{
Page.IsValid = false; // Error because read-only
// Stop before running MyBtn_Click2!
}
}
If my captcha fails validation, I want to return to the page immediately, before it starts running the 2nd click event. Any ideas on how to do this?
I would personally use a hidden field and mark it as required. Put a default value in it, and if your captcha fails, remove the value and revalidate the page.
if (!CaptchaControl.IsValid)
{
myHiddenField.Value = null;
Page.Validate();
}
If your myBtn2 control is using if (Page.IsValid) to execute code, the hidden required field should be empty and now invalid.
How can I invalidate the page in textchanged event.
I have a simple form with textboxes and a button to submit
I would like to disable the button or stop the submission if the text entered is not valid.
the validity is to be checked in the textchanged event since I have some db operation to check the validity of the content.
If I can somehow invalidate the page in the textchanged event then it might be easier
pls give me some easy way to implement this
thanks
Shomaail
I was able to resolve my own problem perfectly. I used the customvalidator OnServerValidate Event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.onservervalidate(v=vs.110).aspx
Now in my TextChanged event I show up a warning if the data entered is not correct and in the button_click event of my submit button I call Page.Validate() that subsequently calls OnServerValidate event handler of each custom validator associated with a text box.
protected void btnIssueItem_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid)
return;
....
}
protected void tbRoomID_CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
BAL bal = new BAL();
args.IsValid = bal.GetRoomByRoomID(Int32.Parse(args.Value)).Count == 0 ? false : true;
}
You can set Button Enabled Property to true of false, ie:
<asp:TextBox runat="server" ID="txtData" OnTextChanged="txtData_TextChanged"
AutoPostBack="true"></asp:TextBox>
<asp:Button runat="server" ID="btnSave" OnClik="btnSave_Click"></asp:Button>
On Code Behid:
protected void txtData_TextChanged(object sender, EventArgs e)
{
if(txtData.Text == "something")
{
btnSave.Enabled = True;
}
else
btnSave.Enabled = False;
}
I have two buttons with on click functions
The 1st one gets assigned a variable when Clicked.
How do I get my second button to get the variable from the 1st button when I click button 2?
It doesn't seem to work. As the second button doesn't recognise the Variable.
Thanks
EDIT:
Just to clarify My code is generating a pdf. button 1 selects the url of the template to use. and in button 2 (the one generating the pdf) I want it to get the variable set from button 1 so it knows what template to use.
EDIT 2:
My code does work but only when I'm not using the ajax update panel. it seems that the variable I'm trying to set doesn't get set with AJAX
Your Button have Id, you get this button with his Id
Nota : You can add runat="server" in order to visualize in server side
<asp:Button id="Button1"
Text="Click "
OnClick="Btn1_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Click "
OnClick="Btn2_Click"
runat="server"/>
void Btn2_Click(Object sender, EventArgs e)
{
Button1.Text = "test after click on button 2";
Template = ...;//Set your value
}
void Btn1_Click(Object sender, EventArgs e)
{
Button2.Text = "test after click on button 1";
//Here you can get your value after post.
var result = Template;
}
It's not subject but in delegate you can also get objet button by passing on sender argument.
var button = sender as Button; //You get button who raise event
In order to manage Template Path property.
public string Template
{
get
{
if(ViewState["Template"] != null)
{
return (string)ViewState["Template"];
}
}
set{ViewState["Template"] = value;}
}
i guess you are looking at accessing value of a variable inside the click event of button2 for which the value is set in the button1 click event ?
private string myPrivateString = "";
void Page_Load()//Not sure of correct method signature
{
if(Page.IsPostBack)
{
myPrivateString = Session["myPrivateString"];
}
}
void Button1_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
myPrivateString = "Value Set From Button 1";
Session["myPrivateString"] = myPrivateString;
}
void Button2_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
//Accessing myPrivateString here without setting value from session
//will return empty string as after PostBack its a new page thats rendered.
myPrivateString = Session["myPrivateString"]; // Or do it in the Page_Load event
}
I guess now you can get the value of inside the button2 click event.
Also read about ASP.NET Page lifecycle and how client side events like button clicks are handled by the ASP.NET framework.