HTML button onserverclick event doesn't work - c#

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.

Related

onclick event is not fired by input buttons inside a user controls

I've updated my .Net web application to use Framework 4.5, after the update, all the input buttons (not asp:Buttons), have stopped firing the onclick javascript code, this is only happening on those buttons that are inside a user control (.ascx).
Just for the record, user controls are neither being loaded dinamically nor inside update panels.
My buttons look like this
<input id="cb" onClick="myfunc()" type="button" value="Close" />
My user controls are included to the page as follows
<cc:actionbar id="theActionBar" runat="server"></cc:actionbar>
and the javascript function, which is also included within the user control, is
function myfunc() {
if (confirm("Before closing, please make sure you saved any changes.\nAre you sure you want to close?") == true) {
__doPostBack('theActionBar:theClose', '');
}
}
this works just fine on Framework 3.5 and previous versions.
any idea why is this happening??? or how can I solve this?? I have tried several suggestions I've found over the internet and nothing seems to work.
Thanks in advance.
.
I can't see an obvious reason, but have you considered simplifying your approach to avoid the custom javascript and hard-coded postback event reference? You can get exactly the same behaviour with an ASP.NET button's OnClientClick property:
<asp:Button runat="server" ID="btnClose" Text="Close" OnClick="btnClose_Click" OnClientClick="return confirm('Before closing, please make sure you saved any changes.\nAre you sure you want to close?')" />
Returning false from the OnClientClick code or function prevents the postback.
Switching to this approach may be preferable and may even solve your issue if it's something to do with the postback event reference.

Skip to Content Link

I am trying to put a Skip to Content link within my web application, but am having some issues.
Currently I have
<asp:LinkButton id="linkSkiptoContent" runat="server" OnClick="linkSKipToContent" Text="Skip to Content"></asp:LinkButton>
within the asp page
and an onClick event receiver
protected void linkSkipToContent_Click(object sender, EvenArgs e){
checkbox.Focus();
}
I am trying to avoid javascript because users have the option to disable it, which would render the link useless. And I know the checkbox.Focus() works properly, since I stuck it in the Page_Load() method and that worked at intented. However, what happens is clicking the link causes it to be focused after the onClick event completes.
Just print an anchor:
<a name="content" />
And link to it:
Go to content
Don't need JS or serverside stuff for that.

Detect which button is clicked in Page_Load?

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

Get the validationgroup that is used on a postback

I'm working with a legacy project in C# (.NET 2.0). In this project there are two validationgroups. One for custom login control and one for users to submit to a newsletter. The problem I ran into is that when a user submits to subscribe to a newsletter some custom code is triggered in the page_prerender() method which only should be triggered when a user tries to login.
I have been looking for a solution to recognize which of the two groups is used on postback so I can ignore the custom code when needed. My idea was to try and check which of the two validation groups is being used to validate. Unfortunately after spending a fruitless few hours on google I've not been able to find anything to let me know how to actually known which validationgroup is used when validating. Is there any way to find out?
<asp:Button ID="btn_newsletter"
runat="server"
Text="Verzend"
ValidationGroup="newsLetter"
meta:resourcekey="bnt_newsletter"
OnClick="handleNewsLetter"
CssClass="roundedButtonBig"
/>
<asp:Button ID="LoginButton"
runat="server"
CommandName="Login"
Text="Inloggen"
ValidationGroup="lgnUser"
meta:resourcekey="LoginButtonResource1"
CssClass="roundedButtonBig"
/>
The following code should only trigger when the LoginButton is pressed and it needs to be done on Pre_render(). Or alternatively pass the correct ValidationGroup (where now null is passed).
protected void Page_PreRender(object sender, EventArgs e)
{
//Register custom ValdiationErrorService added errors to JavaScript so they can be added into the popup.
ValidationErrorService.RegisterServerValidationMessageScript(Page, null);
}
to check which validation group is valid, call:
Page.Validate(“newLetter”);
then check
Page.IsValid;
this will return the value. Scott Gu has more on his blog
edit you are also wanting to know which button was clicked within the prerender event it sounds like as well. While you can't find that out from the parameters passed into the page prerender, you can rely on the button events occuring prior to the page_prerender event. within the aspx pages code behind, create a member variable. this variable will be used to denote if the prerender logic should be executed.
next, within the click events of the two buttons, set that local variable to denote if that button should fire the logic you want in the page_prerender event.
last, check your local variable within the page_prerender method, and encapsulate your logic within an if statement based upon your new member variable.
Happy Trails!

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