Detect which button is clicked in Page_Load? - c#

In my asp.net web page, there are a few of buttons and checkboxs. They all can cause postback.
Can I detect which control is clicked? Because I will add code for if clicked a button then do something.
I saw that some examples are done with Jquery.
Can we just do it in C#?
Thanks.

Why are you not just using the click behavior of the button:
ASPX
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="GreetingBtn_Click"
runat="server"/>
CS
void GreetingBtn_Click(Object sender,EventArgs e)
{
}
reference here

You could check Request.Form["_EVENTTARGET"] for the control that generated the postback

well if each of the buttons submit a key value to the post or get parameters, and theyre all different it should be pretty easy! :)
localhost/home.html?button=clicked&link=selected
the above is an example of a get parameter url, you can use jquery to get those, or if its a post you would have access to them in a similar way...the previous page would have to have been a form though.

You could eventually do it by checking Request.Form["_EVENTTARGET"] but that is highly unusual and certainly not necessary.
Whatever you need to do, you can do it in the Click event handler of the given control.

You can set a server hidden control specifying the action (checkbox/textbox/button clicked) using javascript & retrieve that server control in page load to check its action & add your code for that action

Related

HTML button onserverclick event doesn't work

I'm trying to use the onclickserver on ASP.net to do something when the user clicks on a button but when I click the button nothing happens.
I really can't see what I'm doing wrong.
Here is the button:
<button id="BttnLead" class="bttnBlck" runat="server" onserverclick="BtnLead_OnClick">Lead</button>
And here the event I'm trying to use:
protected void BtnLead_OnClick(object sender, EventArgs e){}
Thank you.
I would bet it has to do with failed validation somewhere on the page, as #kman pointed out in a comment above. Are you using any <asp:FieldValidator/> controls anywhere on the page? If so, and they're not being handled correctly, all you would need to do to cause this button's postback to be triggered is to add the CausesValidation="false" property to the <button> control. This would have the button avoid the validation code that is (if it's the issue, which I really think it is) inevitably failing and thus never reaching the handler method.
P.S. It should be noted that you do NOT have to use an ASP.NET control (i.e. <asp:Button>) and the pure HTML <button> control with the runat="server" property renders a server side control just the same. However, if you're in the ASP.NET world anyway and you have access to these controls, they do provide some benefit that is nice; but that's a different conversation.

ASP.NET WebForms Confirm

I'm new to web programming with .NET.
I am developing a web page with webforms, and I want at a certain moment to programmatically show a modal window, for the user to accept or cancel, according to a question. Exactly what does the "confirm" function of JavaScript.
I tried to get it calling a JavaScript function:
Page.ClientScript.RegisterStartupScript (this.GetType (), "CallMyFunction", "MyFunction()", true);
But I need to do it without reloading the page, and I also need to control if the user has accepted or canceled and I do not know how to do it.
I've also tried getting it using the ModExPopupExtender control from DevExpress.
Can someone tell me a simple way to get what I want?
I can not understand how something so usual in web programming, and that PHP + javascript would not pose any problem can be so complicated.
All start in a one-button event on the code behind:
protected void btn1_Click(object sender, EventArgs e)
{
//I make a series of checks
//If certain conditions I want to show the confirm
//According to the user has chosen ok or cancel will perform a certain action
}
Onclientclick does not help me because before launching the "confirm" I have to do some checks on the server side.
Thank you very much.
You can use OnClientClick which is a property on most web controls.
I like to just bring up a simple confirm() dialog which executes the server code if the user clicks OK and does nothing if the user cancels the action:
<asp:Button runat="server" ID="btnSave" Click="btnSave_Click" Text="Save"
OnClientClick="return confirm('Are you sure you want to do this thing?');" />
You can do other things with it as well, but the key thing to remember is that anything you do in OnClientClick will happen before the page gets posted back to the server.
This is also perfectly valid:
<asp:Button runat="server" ID="btnSave"
OnClientClick="showModalConfirm('some message goes here');" ... />
<script>
function showModalConfirm(msg)
{
$(".modal .message").innerHtml(msg);
$(".modal").Show();
}
</script>
You can set the action that OnClientClick should perform in your codebehind in exactly the same way:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you want to do this thing?');";
}
You can use below code in c# to call javascript function. Below code will execute afterpostback() javascript function:
ClientScript.RegisterStartupScript(GetType(), Javascript, "javascript:afterpostback();", true);
And you can write code in javascript function to display any div or popup:
<script language="javascript" type="text/javascript">
function afterpostback() {
//Here you can write javascript to display div/modal
}
</script>
One way I've handled this previously was to have 2 buttons on the page. The first would be initially visible and labeled "Submit". The second would be initially hidden and labeled "Confirm". The "Submit" button would postback upon click and perform your server side checks/validation. If those checks failed, an appropriate error message would be displayed. If those checks passed, an appropriate "Please confirm your submission"-type message would be displayed, the "Submit" button would become hidden, and the second "Confirm" button would become visible. When that Confirm button was clicked, it would postback again and fully submit.
EDIT: I forgot to mention, there's a bit more to this that occurred to me after I initially posted. You'll have to protect the fields from being edited in the event the server-side verification is successful as you obviously don't want the user changing values and then clicking the Confirm button. That means disabling all the input controls - which could be a pain if you have a lot. You also have to give them a way to (intentionally) Edit in case the server side verification passes, you display the Confirmation, and they change their minds - so basically you'd need a third "Cancel/Edit"-type button that would put the form back in edit mode and show your initial Submit button.

asp.net Button OnClick event not firing

I have problem in asp.net button control.
I define a button in form, onclick event of button is not firing when I click on the button.
<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" />
protected void btn_QuaSave_Click(object sender, EventArgs e)
{
}
Because your button is in control it could be that there is a validation from another control that don't allow the button to submit.
The result in my case was to add CausesValidation property to the button:
<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" CausesValidation="False"/>
Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button.
this should work
I had the same problem, my aspnet button's click was not firing. It turns out that some where on other part of the page has an input with html "required" attribute on.
This might be sound strange, but once I remove the required attribute, the button just works normally.
If you are using updatepanel on onclick event, this may happen.
Use 'EnableEventValidation="false"' in your page markup like this :
<%# Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>
Hope this helps
I had a similar issue and none of the answers worked for me. Maybe someone finds my solution helpful. In case you do not mind submitting on button click, only attaching to click event setting UseSubmitBehavior="false" may be worth trying.
In my case I put required="required" inside CKEditor control.
Removing this attribute fixed the issue.
Before
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server" required="required"></CKEditor:CKEditorControl>
After
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server"></CKEditor:CKEditorControl>
i had the same problem did all changed the button and all above mentioned methods then I did a simple thing I was using two forms on a single page and form with in the form so I removed one and it worked :)
Try to Clean your solution and then try once again.
It will definitely work. Because every thing in code seems to be ok.
Go through this link for cleaning solution>
http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/
Try to go into Design mode in Visual Studio, locate the button and double click the button that should setup the event. Otherwise once the button is selected in Design more, go to the properties and try setting it from there.
Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button
in my case:
make sure not exist any form element in your page other than top main form,
this cause events not fired
If the asp button is inside tag then also the Click event will not raise.
Hope it's useful to some one.
In the case of nesting the LinkButton within a Repeater you must using something similar to the following:
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="MyUpdate">LinkButton</asp:LinkButton>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("MyUpdate"))
{
// some code
}
}
If it's throwing no error but still not firing the click event when you click the submit button, try to add action="YourPage.aspx" to your form.
Even i had two forms one for desktop view and other for mobile view , Removed one formed worked for me . I dint knew asp.page should have only one form.
Try this onserverclick
<button id ="DemoButton" runat="server" onserverclick="button_Click">Login</button>

create a back button that uses javascript or respose.redirect

Im using asp.net c# (webforms)
I want to add a back button to my page. (you land on this page if you incorrectly fill in a form).
if javascript is enabled i want to go back via javascript, but if it is disabled i'll just do a response.redirect("~/home.aspx")...
how can i implement this? is it 2 buttons? how can i hide the other in the 2 different states if so.
thanks
<asp:Button OnClick="serverMethod" OnClientClick="return(jsMethod);" runat="server" ID="redirectButton" Text="Back" />
on the button, but set the OnClientCLick to:
return(javascriptredirect());
and the OnClick to your button click event handler in your code behind.
if javascript is enabled, it will do the javascript redirect, if not enabled the page will post back and you can do your OnClick code behind method whic can to the response.redirect. You can also return false from your function to prevent the postback from occurring such as the case with setting the OnClientClick="return(confirm('Are you sure?'));"
This link guides you how to do it http://aspadvice.com/blogs/azamsharp/archive/2007/09/30/Check-If-the-JavaScript-is-Enabled-on-the-Client_2700_s-Browser.aspx
Happy coding !!!!!!

ASP.NET 2.0 - Need to programmatically click a link

Is there a way to click a link programatically, so that it has the same effects as if the user clicked on it?
Example:
I have an ASP.NET LinkButton:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass">Export</asp:LinkButton>
I have a link on a sidebar directing to the .aspx page that has this linkbutton on it. For various reasons I can't have the code for the LinkButton executed until the page has refreshed -- so I am looking for a way to force-click this LinkButton in my code once the page is completely loaded. Is there a simple/doable way to accomplish this? If it involves triggering an event, please provide a code sample if you can. Thanks.
Triggering a click event programatically on a link will trigger the “onclick” event, but not the default action(href).
And since linkbuttons come out as hrefs, so you could try doing this with Javascript.
var lnkExport = document.getElementById('<%= lnkExport.ClientID %>');
if(lnkExport){
window.location = lnkExport.href;
}
I certainly think that, there is a design and implementation flaw which forces you to conclude as you described.
Well, invoking the click event means nothing but executing the event registration method.
So, the worst suggestion I can think of is, just call the function at what point you want to happen the click event like,
lnkExport_Click(lnkExport, new EventArgs());
Rashack's post show's how to do it. You can just do it in javascript.
function ClickLink() {
document.getElementById('').click();
}
If you want this to fire after some other event, you can add code in c# to add a call to that function on the client side when the page loads.
Page.ClientScript.RegisterStartupScript(
this.getType(),
"clickLink",
"ClickLink();",
true);
I'm not sure why you'd need your page to load if you're just wanting to programmatically click that link. I'd recommend using Response.Redirect() on the server side to redirect them to that page. Not sure if there are other extenuating reasons this simple approach won't work...
--Matt
If i understand what you're saying:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass" onclick="lnkExport_Click">Export</asp:LinkButton>
then in your codebehind or whenever call the following when you need to...
lnkExport_Click( null, null );
and make sure you've got lnkExport_Click wired up.
protected void lnkExport_Click( object sender, EventArgs e )
{
//DO Whatever here
}
<button onclick="document.getElementById('<%=this.lnkExport.ClienID%>').click()">
click me</button>

Categories