OnClick not working when i use both Onclick & OnClientClick - javascript

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

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
}

How to display confirmation message when a user clicks a checkbox

I'm having issue trying to display a confirmation message when a checkbox is clicked. The confirmation box appears but doesn't perform any type of action such as displaying the text within the textbox when the user confirms OK. Any advice would do. Thanks in advance!
Here is the code.
<div>
<asp:CheckBox ID="CheckBox1" runat="server"
OnCheckedChanged="CheckBox1_CheckedChanged"
OnClick="if(!confirm('Are you sure you?'))return false;" />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "blah";
}
Well, a check box is not like a button. There is no OnClientClick for a check box.
However, you CAN use OnClick.
Also, the code stub (code behind) you have does NOT run like a button click UNLESS you set AutoPostback = true.
However, you can do it this way:
<asp:CheckBox ID="CheckBox1" runat="server"
OnClick="if (!confirm('really do this')) {return false;}"
AutoPostBack="True"/>
You have to use the !not, and exit from the JavaScript routine, or you MUST LET the JS code continue, since it will do a post back for you. So, the above code spit out by asp.net becomes this:
<input id="CheckBox1" type="checkbox" name="CheckBox1"
checked="checked"
onclick="if (!confirm('really do this')) {return false;};
setTimeout('__doPostBack(\'CheckBox1\',\'\')', 0)">
So, we HAVE to let the js code "continue if we want ok, but if we don't confirm, then we MUST do a return false and exit the js code stub else the post back will in fact run regardless of returning true or false. If fact even if we return true, then the stub exits and the following postback code never will run. So a return with either value still bails out of the generated code stub.
So the check box does NOT support the standard for most buttons in that you use js to return true, or false and thus as a result the post back does not occur.
We can't use say return confirm('Please hit ok') like we can for a button, since if we "return" a value then the post-back code that follows never runs.
So, for a button, the OnClientClick() return value (true/false) is tested for you, and that determines if the button post back will fire. Not so with a check box, and no OnClientClick is defined or supported. But as you can see above we can trick the page processor into working - since it simply appends it own post back code to what we stuff into OnClick.
But, a check box is different, and it does not really support OnClientClick. But if you shove code into OnClick(), then you can see the final rendered output. We thus LET the continue contine to run the postback if we confirm, but bail out (return false) if you don't confirm and the post back code that follows simply does not run.

Save data before leave the page in ASP.NET

I have asp.net page.
I don't have button "Save" on it (not my requirement).
I need to save page data before I leave this page.
I've tried to do it with events like Page_Unload but it doen't work...
Cause Save method uses data from elements on page like txtBox1.Text I can't use .ashx handler to make some ajax save (Or I don't know how to use page elements in handler as they are protected).
So is there any solution except serealizing form and pass it to handler?
You can use the onbeforeunload event.
It should fire before unload.
It allows you to ask back if the user really wants to leave. Check simillar example here.
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
In return you can save you required values.
Alternatively, you can send out an Ajax request when user leaves.
I know its late to answer , but its not late at all for people who is still working on same problem :
you just have to surround your execution function area with update panel like below
<asp:UpdatePanel runat="server" ID="blahblahId">
<ContentTemplate>
<asp:Button CssClass="hidden" runat="server" ID="btnAddInfo" OnClick="execBforeUnload"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddInfo"/>
</Triggers>
</asp:UpdatePanel>
and your javascript code will be
var unloadEvent = function (e)
{
alert("hi");
__doPostBack("<%=btnAddInfo.ClientID%>", "");
};
window.addEventListener("beforeunload", unloadEvent);
Finally your C# method will be as follows:
public void execBforeUnload(object sender ,EventArgs e)
{
Session[lblNumber.Text] = null;
Application[lblNumber.Text] = null;
}

How to disable postback on an asp button and still run OnClick method?

Yes, it is possible to simply add a return false to the OnClientClick, but that's not doing a very good job since the function on the OnClick just stops working.
The function that i use on the OnClick property on the button takes data out of the database and does something with it. while i have that return false there, nothing is happening. When it's not there, the page keeps refreshing and nothing is done.
Please, if anyone got a way to block the postback without blocking the method on the OnClick property that'll be great!
HTML
<asp:Button Text="Edit Ceredntials" OnClientClick="ShowWindow('#EditDetails', 2500)" OnClick="GetUserData" runat="server" />
You can't prevent a postback and still run the OnClick method. That's because OnClick runs on the server, and the only way it can execute is via a postback.
If what you're really trying to accomplish is preventing the page from losing state and refreshing, you should be using AJAX instead and a compatible server side framework, like Web API.
<script type="text/javascript">
function loadUserDetails(){
$.ajax({
url: 'api/Users/2500',
type: 'GET'
})
.success(function(userDetails){
$("#FirstName").val(userDetails.FirstName);
ShowWindow('#EditDetails', 2500);
});
}
</script>
<asp:Button runat="server" OnClientClick='loadUserDetails()' Text="Edit Credentials" />

asp.net - do AsyncPostBack using js

I've spent almost 3 hours for the following case:
I want to trigger an AsyncPostBack from JavaScript but to be able to send same parameter also because I need it on the server side.
I've tried a lot of situations but I am unable to find a clear example.
I have an update panel and when I am pressing a specific image button inside it, some popup is displayed. (the popup is hidden initially, and when the request is done, the display:none is removed=> it appears fine)
function BeginRequestHandler(sender, args) {
}
function EndRequestHandler(sender, args) {
document.getElementById('popup').style.display = '';
document.getElementById('overlay').style.display = '';
}
Well, the issue is that I need to make a js function to do the asyncPostBack because this js function will be called from a flash control when doing click on some portion of that control, so I want to simulate my click on the image. (because doing click this popup is displayed as you see above)
The issue is that I am not able to find anywhere such an example. This js function will receive a parameter so when I do the postback I want to be able to get that parameter on the server side. (this parameters seems to be the main problem =- how I send it to the server when I am doing postback?).
Sorry if I was not very clear, but can you give me some documentation for this or example?
Thanks a lot!
UPDATE:
Please note that the first case I've already done, using an ImageButton in my UpdatePanel:
<asp:ImageButton ID="lnkDetails" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Logo") %>'
AlternateText='<%# DataBinder.Eval(Container.DataItem, "Name") %>' OnCommand="lnkDetails_Command"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TenantID") %>' Text="Click">
</asp:ImageButton></li>
What I only need is to "simulate" this click, using a javascript to make the async post back (because when I will call from flash, flash control will call my js method for postback)
To initiate an async postback from javascript:
__doPostBack(target,args)
target is the UniqueID of the UpdatePanel you want to target. Usually it works fine to just pass an empty string (will refresh all auto-updating panels).
The 2nd parameter is arguments that you can use for whatever you want.
Both will be available to you on the server:
Request.Form["__EVENTTARGET"]
Request.Form["__EVENTARGUMENT"]
This should work quite well:
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick='return doSomething(<%#Eval("SomeValue")%>);' />
EDIT: Try wrapping your JavaScript function with this:
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () {
doSomething = function(argument){
__doPostBack("<%=ImageButton1.ClientID%>", argument);
return true; //don't know if you need this
}
});
EDIT: Check your ScriptManager and make sure that EnablePartialRendering is set to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" ... />
In the code-behind:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);
if (source == ImageButton1)
{
string arg = eventArgument;
}
}

Categories

Resources