Button is not triggering in ASP.NET Webforms - javascript

I'm trying to fix a bug I've encountered with a button not triggering in my webform.
The code for the button in the aspx file and the vb file looks like this:
<asp:Button ID="btnUserEditSave" runat="server" Text="Save User" ClientIDMode="Static" CssClass="button saveButton xbtnWaitEvent" width="100px" ToolTip="Save changes" />
Protected Sub btnUserEditSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUserEditSave.Click
I haven't included to code for the button itself as it's irrelevant because the bug relates to the button not triggering rather than the code of the button itself breaking. I've tested how the button works and what causes it to not trigger and here's the information I have thus far:
When first saving user details through this button, the button triggers and all code runs as expected. The page is the reloaded with the new user details showing.
However after doing this, the button will not trigger properly and when clicked will cause the page to go blank. This is despite the fact that no page load methods written in the source trigger either nor does the Javascript seem to either which I've tried testing through the use of alerts (see code below):
if(document.getElementById('btnUserEditSave').clicked == true)
{
alert("button was clicked");
}
It is worth noting that the other buttons on the page also do not work again in a very similar way. The code behind the button does not trigger nor does a page load method trigger. But a blank page is still shown.
If any further code is needed for context then I will provide as much as I can, and any help as to what might be causing this error would be greatly appreciated as I am rather stuck for ideas. Thanks.

You need to add the onclick event in the html markup, that's how you wire it up.
<asp:Button ID="btnUserEditSave" onclick="btnUserEditSave_Click" runat="server" Text="Save User" ClientIDMode="Static" CssClass="button saveButton xbtnWaitEvent" width="100px" ToolTip="Save changes" />

Related

How can prevent postback page in the case of using both a JavaScript and a C# method on a button?

This is an ASP.NET C# question.
<script>
function buttonfunc() {
document.getElementById("demo").innerHTML = "js work";
}
</script>
<form id="form1" runat="server">
<div>
<p id="demo"></p>
<asp:Button ID="UpdateButton" runat="server" Text="Update"
OnClick="UpdateButton_Click" OnClientClick="buttonfunc()"; return false;/>
</div>
</form>
protected void UpdateButton_Click(object sender, EventArgs e)
{
Response.Write("cs work");
}
In the case of using both a JavaScript and a C# method on a button, how can we stop postback page and display two lines of text at the same time (if possible, without using AJAX)?
The way this works is rather handy.
While that button can have both a client side event, and a server side event?
If the client side js code/event returns false, then the server side event will not trigger. This is ideal for say prompting a user to delete a record, or to perform some operation that you require a "confirm" for.
so, take this button:
<asp:Button ID="cmdDel" runat="server" Text="Delete record"
CssClass="btn"
OnClick="cmdDel_Click"
OnClientClick="return DelConfirm()" />
<script>
function DelConfirm() {
return confirm("Really delete this reocrd?")
}
</script>
so, if the js code (client side) returns true, then server button click runs. If client side js code returns false, then server side button does not run.
You would see this for running above:
and display two lines of text at the same time
Hum, that is not clear what you goal here. What 2 lines are you looking to display here?
I mean, either you want/have the server side button event code run, or it does not. As noted, if you return false, then you should not be seeing a post-back. With your sample code, the return false should result in the server side button even NEVER running.
I mean, if you don't do a post-back, then it does not make sense that you can/will have the server side button code run. You require a post-back for this to occur.
Now, you might be able to live with a update panel, and that allows you to define ONLY that part of the web page that will travel up to the server, and run your code. From a user point of view, the page will not appear to have a post back (and you don't actually have a full page post back in this case). The brower scoll bar will not change postion, and you not see the browser "spinner" show a post-back.
So, you drag + drop in the script manager, and then inside of the update paneel, you would have this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete record"
CssClass="btn"
OnClick="cmdDel_Click"
OnClientClick="return DelConfirm()" />
<script>
function DelConfirm() {
return confirm("Really delete this reocrd?")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Now, in your code exmaple, place everything inside of the content template, and remove your return false for the client side click. give it a try.
Now, some caution with above. The page life cycle DOES trigger. So, the page load event will fire (like it always does), and then your code stub will run. but to the user, you not see a full page post back. This is often called a "partial page" post-back.
Needless to say, to build a working web forms page, 99% of the time, your page load event that sets up values for controls and does things on the FIRST page load ONLY?
You have the !IsPost back stub in the page load event, so your REAL first time page load code only ever runs one time.
eg:
if (!IsPostBack)
{
// first time page load
// load up grid, some combo boxes etc.
// this code only runs ONE time, on first page load
}

ASP button OnClick not firing in javascript popup

I am attempting to submit form data from within a javascript popup window.
The popup opens fine and displays all elements as expected. When I click the asp:button, before inputting anything, it performs required field validation as expected. All of that is working just fine.
The problem I am having is in getting the OnClick to work and submit the form data.
To say I am a beginner to javascript/JQuery is an understatement, so requesting a bit of hand-holding on this one. Thanks in advance for the help.
<asp:Button ID="submitRes" CssClass="button" runat="server" ClientIDMode="Static" Text="Submit This Form Data" OnClick="Submit_Click" />
$( document ).ready(function() {
$(document).on("click", ".divPopupAdd", function(event){
showPopup()
});
function showPopup(){
$("#popup_add").dialog({
show: { effect: "blind", duration: 200 },
resizable: false,
modal: true,
width: 750,
height: 450,
open: function(){
$('#<%=submitRes.ClientID %>').click();
}
});
}
});
Ok, this is how you post back - click a button to run your code behind.
We going to lay this out step by step.
We assume, that you click a button on your form, and it launches the jQuery dialog? Beyond important here that this “is” in fact your flow in this form.
So, I’m going to assume user clicks a button, and the dialog is launched.
(and avoid that document on-ready. Please dump it).
Now the dialog is displayed. In that dialog, we assume user enters data, does whatever, and THEN either clicks a button for ok, or clicks a button to cancel?
Next up:
You CAN NOT do/use an asp.net button for a post back in that dialog. It WILL NOT work – end of story!
And if you did get the post back to work, it would mess up your current page “dom” that is holding the current web page, and also that of the dialog. It just does not work – don’t do it, ok?
(so no post backs in that dialog!!)
But we can still happy make this work!!!
So, how do we setup a button in the dialog?
Lets assume you need to click a button inside the dialog?
Button MUST be client side JavaScript (js).
That button will:
Close the dialog, and THEN do the post back.
So, we thus need this flow:
Display dialog on button click (client side js).
User does whatever in that dialog.
User now clicks on a button (say ok, or cancel).
We CAN and will for the sake of going crazy? We will drop on the form and use standard asp.net buttons. There is really no need to adopt HTML “input” buttons. (You can, but no real need here).
I am going to use BOTH built in jQuery buttons and ALSO two standard buttons in that dialog (the reason is many, but that way YOU can choose either way, and learn this. (boy, do I with someone had laid out how this works for me!!!). So, I going to save you much pain and suffering here.
So, lets start from the top:
Our button code to pop the dialog.
The asp button will be this:
<asp:Button ID="showdialog" runat="server" Text="Show the dialog"
OnClientClick="showpop();return false;"/>
Note close in above!!!!
We use OnClientClick=showpop();return false.
This will thus run js code, and NOT do a post back. The return = false is VERY important here, since if you leave that out, then the standard asp button will post back like it “normally” does. And we break our new rule!! – no post backs inside the dialog!!.
Ok, so that is the button to launch the dialog.
The js code to launch the popup is similar to what you have.
Eg this:
function showpop() {
var mydiv = $('#popdialog');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool dialog, width: '30%'
});
// Open the dialog
mydiv.dialog('open');
}
Now, again for this example, we assume that you dropped some standard asp buttons in that dialog. But, OFTEN you want to use the built in dialog buttons. So let’s do BOTH for this example.
So, the above code thus becomes this:
function showpop() {
var mydiv = $('#popdialog');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool other page', width: '30%',
position: { my: 'top', at: 'top+150' },
buttons: {
'ok': mycustomok,
'cancel': mycustomcancel
}
});
// Open the dialog
mydiv.dialog('open');
}
Note the two built in buttons we added. (ok, and cancel).
Note how I also broke out the 'setup' and THEN the one line that pops the dialog.
And in our pop up div, we also have two custom buttons. As noted, I am including both custom and built in dialogs. This will take you “hours” to get nice examples of this, and now you can choose either road.
So, our div has some text, and two custom buttons, and a simple text box.
The div looks like this:
<div id="popdialog" runat="server" style="display:none">
<h2>My cool pop dialog</h2>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="MyOk" runat="server" Text="My custom ok"
OnClientClick="mycustomok();return false;"/>
<br />
<asp:Button ID="MyCancel" runat="server" Text="My custom cancel"
OnClientClick="mycustomcancel();return false;"/>
</div>
The only real thing to note in above is the style=”display:none” for the WHOLE “div”. This will thus hide the div, and it will not display when the page loads.
So, when we click on the button, it will show the dialog. You will see this:
So, we have our two custom buttons, and the two jQuery but in buttons. If you don't want the built in ones then use my first sample code. As I stated, your choice as to which buttons you want, like, or feel to use here. The main point is that BOTH sets of buttons do the SAME thing.
So, for this example, you click “ok”, or “my custom ok”.
Either way? We want our post back to run for that choice.
And for my custom cancel, or the built in cancel, we want code behind (server code) to run for that cancel choice. Do keep in mind you often don't need any code - but JUST the dialog to close and cancel and do nothing.
So, the two js stubs we have for this are:
function mycustomok() {
// first, close the dialog
$('#popdialog').dialog('close');
#('#HiddenOk').click();
}
function mycustomcancel() {
// first, close the dialog
$('#popdialog').dialog('close');
$('#HiddenCancel').click();
}
As noted, if you use BUILT IN buttons for the dialog, then you do NOT need the “close” of the dialog I have above. But your using (we assume) custom buttons, and not the built in jQuery ones.
And as noted, based on either choice, we will do a post back and run code behind. As I stated, the short way, easy way is to drop two hidden buttons on the form, they will look like this, and of course our outside the above div
<asp:Button ID="HiddenOk" runat="server" Text="hidden ok"
style="display:normal"/>
<asp:Button ID="HiddenCancel" runat="server" Text="hidden cancel"
style="display:normal"/>
Note careful (note BEYOND carefull here).
I have display = normal for the two buttons. The reason is that then with the designer you can double click on the button, and write your code behind. When you are DONE and have both code behind stubs written, then change the above display:normal to display:none to hide them. So we left the buttons visible for easy development. Once you wired up the code behind (simply double click on the buttons in the designer), then you are jumped to the code behind editor, and can write that code.
I have this for now:
Protected Sub HiddenOk_Click(sender As Object, e As EventArgs) Handles HiddenOk.Click
Debug.Print("dialog ok code run")
End Sub
Protected Sub HiddenCancel_Click(sender As Object, e As EventArgs) Handles HiddenCancel.Click
Debug.Print("dialgo cancel code")
End Sub
Of course you write whatever you need. As noted, you may well not need any code for the cancel button – you can leave that out of this design if you wish.
So, with the two code subs automatic wired up for you (this is why we all love asp.net forms, right???).
The “click” button trick as noted is rather nice. It solves a LONG list of issues, and does so with great ease.
You get the needed post back.
You get to run your own cute little code stub behind.
You don't have to write up ajax calls to do this!!!
So this follows the whole asp.net design pattern in which you drop buttons on a form, click them, and you get to run that nice little short code behind stub. And it all wired up automatic for you.
Thus in summary:
Don’t try + attempt post backs in the dialog – you REALLY can’t do this.
And you find they don’t work anyway! So buttons on that dialog WILL run “js” code.
you can use asp buttons if you want, just remember the extra return=false part.
If you must set/send some information to the server in that dialog before you close? Well, that is a different question and answer. But the jQuery "ajax" method works REALLY nice, and you can directly call functions in your existing web page code behind, and do so with next to no effort. You don't even have to know how to setup web methods - asp.net will do all the dirty work. but lets leave that example for another day.
Try the above idea - the "click" button trick in js really is the magic key to making this all oh so very easy to write and setup.
If you wish to call the JavaScript popup from Backend side you can use ClientScript.RegisterStartupScript
Syntax:
ClientScript.RegisterStartupScript(Type type, string key, string script, bool addScriptTags)
Parameters
Type: The type of the startup script to register. This is of type 'Type'
key: The key of the startup script to register. This is of type String
script: The startup script literal to register. This is of type String
addScriptTags: A Boolean value indicating whether to add script tags. This is of type bool - true or false.
You can write like this:
protected void Button_clilck(Object sender, EventArgs e){
ClientScript.RegisterStartupScript(GetType(), "Key","showPopUp(),true);
}
And if you want to call your pop up method from Front End side you can simply call the JS method in asp:button by writing OnClientClick
<asp:Button ID="submitRes" CssClass="button" runat="server" ClientIDMode="Static" Text="Submit This Form Data" OnClick="Submit_Click" OnClientClick="showPopup" />

OnClick not working when i use both Onclick & OnClientClick

With this code, i try to Close a Window (the way i'm doing it works) but i have also an Onclick event which is ignored!
<script type="text/javascript">
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseDialog() {
GetRadWindow().close();
}
ASPX page:
<asp:Button ID="Button1" runat="server" Text="Soumettre ce ticket"
onclick="Button1_Click" OnClientClick="CloseDialog();return false;"/>
My application never enters Button1_click event, can anyone help me to find out why ?
thanks in advance
EDIT: HTML GENERATED FOR THE BUTTON
<input type="submit" id="Button1" onclick="CloseDialog();" value="Soumettre ce ticket" name="Button1"/>
This article kind of explains the problem. You need to return true in your JS if you want the server event to trigger. Otherwise, you have to return false.
And, it also looks like you will have to add the UseSubmitBehavior = false based on: OnclientClick and OnClick is not working at the same time?
This is especially evident after seeing that your generated HTML only has the CloseDialog() and not the call to Button1_Click. This change will concatenate to the end of your onclick.
<asp:Button ID="Button1" runat="server" Text="Soumettre ce ticket"
onclick="Button1_Click" OnClientClick="CloseDialog();"
UseSubmitBehavior="false"/>
I ran into this problem and using UseSubmitBehavior="false" nearly did the trick. Be sure to have your OnClientClick call set up correctly:
My code was using OnClientClick="return ValidateSearch();" which is incorrect. It should just be
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click" OnClientClick="if (!ValidateSearch()) { return false;};" />
See the Source here (and tell them thanks!)
If it is set up incorrectly, the OnClick function will not fire.
You are returning false in the onclientclick, so the event is returned before the postback. As a result, onclick never fires.
I just came across the same issue, and I think we're getting confused between server side enable="false" and client-side "disable".
The serverside property to enable a control using control.Enabled = "false"; is not the same as applying an Attribute, like control.Attribute.Add("disabled","disabled");
If you apply the Enabled = false; from the server side, you're actually turning off the control entirely, even if it's shown on the screen! Go on, try and right click the control and select Inspector or FireFly to see it. Nothing shows up. Nothing happens, because the control does not "exist".
Yet if you apply the Attribute property the control is visible to the server and the client, and you're able to inspect it.
What I did is set up the default environment on the ASP.net side by saying the control (asp:Button in my case), has Enabled="true" (or not saying anything, as that's the default anyway).
On the server side, upon PageLoad(), I make my button Visible (in my case I also had it defaulted to visible="false"), and add the appropriate Attribute values.
btnSEND.Visible = true;
btnSEND.Attributes.Add("disabled", "disabled");
That way the button is not enabled, but it's not entirely "invisible" to the client, and by using JavaScript in another area of my program, I control when to enable it or not.
This method also avoids having to use the UseSubmitBehavior="false".
in page_load, you pass the java script function using Add.Atribute method with return true. first it will load the javascript function. then it will load the button click event

Hiding an applet before a long treatment postback

I have to integrate a Java applet into a simple asp.net 2.0 control.
This applet is a bought product and cannot be modified. It contains a button designed to be clicked to continue. The button click is linked to a JavaScript function.
So we can see this applet as a black box, eating data and calling a JS function when it's done.
I have to make a postback when the JS function is called to go to the next page. Easy, I just have to write it. But I would also like to hide the applet, or the div containing it, because the postback trigger some long treatment. The point is that, while waiting, the user can click on the applet button and triggers the postback again.
In my JavaScript called function, I tried many solutions:
Make 2 postbacks. Of course this doesn't work, as a postback is a reload of the page
Hide/show the div or the applet using JavaScript
Hide/show the div or the applet using jQuery
Hide/show the div or the applet calling the click event of an invisible button to set Visible = false in the code behind
But it always fails: it seems that the web browser (IE 8.0 or Chrome) waits the end of the postback/JS function to update the page, and don't bother with some UI update just before.
So here I am:
I need the postback to go to the next page (I do not control the entire environment where my control is used)
I have to hide the applet, otherwise the user can re-click on it
I can't make a two-step process, like having the JS function hiding the applet and displaying a link to to the next page, involving a new click
My simple control:
<%# Control Language="C#" AutoEventWireup="false" Codebehind="MyControl.ascx.cs"
Inherits="MyControl" %>
<div id="m_DivPostDisplay" runat="server">
<asp:Label ID="lblState" runat="server" Text="Displaying something like please wait..." />
</div>
<div id="m_DivAppletContainer" runat="server">
<applet name="myApplet" archive="./myJar.jar"
code="Main.class" height="700" width="530" mayscript>
</applet>
</div>
The related javascript (injected when the page load):
<script language='javascript'>
function sendData(data) {
// This is where I try to hide the applet or the div
//.....
// Go to the next page
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"nextButtonId\", \"\", true, \"\", \"\", false, true));
}
</script>
Do you have any idea of what could be done to fix my problem?
Thanks :)
Ugly, but you could try :
function sendData(data) {
// hide applet
setTimeout(function () {WebForm_DoPostBackWithOptions(...);}, 500);
}
Finally we asked the applet editor to add a new feature, so we can now disable its buttons when we need.
So when we click on the button, we keep it disabled, launch the postback, and change page when the postback returns.

Extremely laggy Responsiveness of asp.net LinkButton in FireFox inside a UpdatePanel

I have a little problem with a LinkButton in a UserControl based asp.net application. In Firefox, one single click on the LinkButton does not do anything. You have to press and hold the LinkButton for approx. 800ms to successfully trigger the PostBack.
Edit: The Focus outline is lagging too. When i click on that LinkButton, the outline-change needs approximately the same amount of time you have to hold the button the trigger the postback.
notes:
the webapplication and the LinkButtons are working perfectly in IE and Chrome
the javascript libraries (external and internal) are currently neither obfuscated nor compressed
Here's the asp.net markup:
<li id="liMemberGetPerson" runat="server" class="inactive clear">
<div class="tab clear">
<div class="tab-left"></div>
<div class="tab-main">
<asp:LinkButton ID="lbPersonArea" runat="server"
Text="Person" CausesValidation="false"
OnCommand="OnMemberViewAspectChange"
CommandArgument="MemberGetPerson" />
</div>
<div class="tab-right"></div>
</div>
</li>
Edit: the "code-behind":
protected void OnMemberViewAspectChange(Object sender, CommandEventArgs e){
AppAction currentAction = HistoryManagerFactory.GetCommandManager().GetCurrentCommand();
AppAction newAction = new AppAction();
newAction.ViewType = ViewType.MemberView;
newAction.AspectType = (AspectType)Enum.Parse(typeof(AspectType), e.CommandArgument.ToString());
newAction.ObjectID = currentAction.ObjectID;
newAction.Mode = currentAction.Mode;
HistoryManagerFactory.GetCommandManager().AddNewCommand(newAction);
ChangeAspect( newAction );}
The ChangeAspect() method call renders the corresponding View ( UserControl ).
I have tried the following without success:
Disable the Firefox Client Caching
Disabling PartialPage Updates (disabling the UpdatePanels)
If anyone has ever encountered this problem, i'd be very thankful to hear about any possible solutions.
with kind regards
Ole
I have solved the issue and if anybody wants to know, here is the solution.
As you can see in the original question, the LinkButton was part of a List Item (li) block. The list item has been styled to be a tab control with rounded corners for each tab header. The css-class for the <ul> involved in this had the following attribute:
display:inline;
I do not excactly understand, why this has affected the responsiveness of the LinkButton inside, but anyway, removing it solved the problem.
You mention javascript libraries - is it possible that there are there event handlers capturing click events for the LinkButton or its parents? Debug the javascript with FireBug, set a breakpoint at the line of the rendered <a href ... onclick="javascript:WebForm_DoPostBackWithOptions(...)"> tag, click, and see where you're getting held up.
try OnClick event for executing instead OnCommand... Onclick is recognized by all browsers

Categories

Resources