I have searched for hours, but I am lost.
Is there any way to Cancel a OnClick() event from an asp:LinkButton command?
I have the following client side code:
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete" OnInit="SetVisibility" OnClientClick="return confirm('Are you sure?');" Text="Delete" OnClick="LinkButton3_Click"></asp:LinkButton>
The server side code for the OnClick() event is thus ...
//Trap the delete button
protected void LinkButton3_Click(object sender, EventArgs e)
{
try
{
if (ListBox1.SelectedItem.Text == "** NO SCHOOL RECORDED **")
throw new Exception("You cannot delete this entry, as it's the default for every student until a School is selected in Basic Enrolments.");
}
catch (Exception exc)
{
webMessageBox.Show(exc.Message);
return;
}
}
As you can see I want to abort the Delete command if the dropdown in my code has a specific Text.
The Return; statement does nothing. The record still gets deleted!
Is there a way to abort this event, since there is no e.Cancel method?
I've read [this][1] and [this][2], to no avail. The suggestion that there is no way to cancel this event, makes me think that perhaps I should be aborting the delete in the databinding events? Or even better, how to hide the Delete linkbutton if the user selects the above dropdown text?
Thanks in advance.
Thanks
Instead doing it on server side you can do it on client side. You can use require filed validator and use that.
Examples
How to place a required field validator inside a GridView TextBox
How to add a RequiredFieldValidator to DropDownList control?
Or create a javascript or jQuery function on client click and check the dropdown value and do the validation.
UPDATE
I've decided to ditch the OnClick() event entirely and trap the condition using the DetailView's DataBound event. I then checked the value from the dropdownlist and simply hide/show the LinkButton controls as necessary.
ie:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton lnk1 = (LinkButton)DetailsView1.FindControl("LinkButton1");
LinkButton lnk2 = (LinkButton)DetailsView1.FindControl("LinkButton2");
LinkButton lnk3 = (LinkButton)DetailsView1.FindControl("LinkButton3");
if (ListBox1.SelectedItem.Text == "** NO SCHOOL RECORDED **")
{
if (lnk1 != null) lnk1.Visible = false;
if (lnk2 != null) lnk2.Visible = false;
if (lnk3 != null) lnk3.Visible = false;
}
else
{
if (lnk1 != null) lnk1.Visible = true;
if (lnk2 != null) lnk2.Visible = true;
if (lnk3 != null) lnk3.Visible = true;
}
}
Related
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 ?
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;
}
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
}
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.
I found a solution like this but my onclick event is already tied to a code-behind handler:
MyButton.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(MyButton, "").ToString());
onclick="this.disabled=true;__doPostBack('MyContrl$MyButton','');"
My code:
<asp:imagebutton id="CheckoutBtn" runat="server" ImageURL="Styles/Images/submit.gif" onclick="CheckoutBtn_Click">
code-behind:
protected void CheckoutBtn_Click(object sender, ImageClickEventArgs e)
{
{
MyShoppingCart usersShoppingCart = new MyShoppingCart();
if (usersShoppingCart.SubmitOrder(User.Identity.Name) == true)
{
CheckOutHeader.InnerText = "Thank you.";
Message.Visible = false;
CheckoutBtn.Visible = false;
}
else
{
CheckOutHeader.InnerText = "Submission Failed - Please try again. ";
}
}
}
Disabling the Button serverside won't work, the Button will be disabled AFTER the PostBack, in this time the user can still click several times, disabling it in JavaScript this.disabled=true; is the only way to successfully do this.
Cases where you are trying to prevent the user from submitting a form multiple times are best handled using the Post/Redirect/Get pattern.
It is a very simple pattern and Wikipedia does a good job of explaining it:
http://en.wikipedia.org/wiki/Post/Redirect/Get
I assume you want to skip clicks that come within a certain TimeSpan of previous clicks. Create a class variable "DataTime LastClickTime", initially set to DateTime.MinValue. When you enter the click handler, check if DateTime.Now - LastClickTime > TimeSpan(...desired...) and if it isn't, exit the click handler with a return.
Try to disable the button with javascript instead of disabling it server side?
<asp:imagebutton id="CheckoutBtn" runat="server" ImageURL="Styles/Images/submit.gif" onclick="CheckoutBtn_Click" OnClientClick="this.disabled=true;">
One way is hide the button from Javascript and show some ajax loader image.
function btnClientClick()
{
document.getElementById('CheckoutBtn').style.display = 'none';
document.getElementById('dvLoader').style.display = '';
}