OnClientClick OnClick - javascript

In my asp page, I take a screenshot of the client's desktop with an applet and ask them to send it to the server with a single click of a LinkButton. I use runApplet() function to call my applet to capture the screen and assign the strings value to a hidden value. (picture is stored as base64 string) Until here, everything works perfect! However, SendLinkButton_Click doesnt seem to be executing!
This is my link button.
<asp:LinkButton ID="SendLinkButton"
OnClientClick="runApplet(); return false;"
OnClick="SendLinkButton_Click"
Visible="false"
CssClass="portal-arrow portal-button"
runat="server">Send</asp:LinkButton>
This is my Javascript function
function runApplet() {
var msg = document.capture.capture();
var hiddenControl = '<%= inpHide.ClientID %>';
document.getElementById(hiddenControl).value = msg;
}
and this is what's inside of SendLinkButton_Click
protected void SendLinkButton_Click(object sender, EventArgs e)
{
Server.Transfer("Preview.aspx", true);
}
when I put the javascript function to a LinkButton's OnClientClick, and execute this "SendLinkButton_Click" with another LinkButton. It works perfect! But I want them to work with just one click!
Please help!

Your client click is returning false so no postback will be made to the server after this point.
Try changing:
OnClientClick="runApplet(); return false;"
To
OnClientClick="runApplet();"

Remove return false from the OnClientClick attribute. If you return false from it, the postback will not execute.

Related

__doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page

I have identified a problem with __doPostBack and found a work around. I am seeking an explanation for the cause and/or a better solution than my work around.
Scenario:
I have a dropdown populated with the values; "-Select-", "One" & "Two". If the user selects "One" than client side script is executed. If the user selects "Two" than server side script is executed.
Problem:
The client script initiates the postback by calling __doPostBack. However, no post back actually occurs unless there is also a LinkButton, Calendar or WizardStep control on the page. I actually went through all of the standard tools in the Visual Studio Toolbox and tested them all. It has to be one of those three.
Work Around:
Add a link button surrounded by a span with display set to none.
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Question: Can somebody provide an explanation for this behavior or provide a better fix than my "Work Around"?
Source - Javascript (I placed it between the head tags)
<script language="javascript" type="text/javascript">
function DropDownList1_change(elementRef) {
var selectedIndex = elementRef.selectedIndex;
if (selectedIndex > 0) {
var selectedValue = elementRef.options[selectedIndex].value;
if (selectedValue == "One") {
alert("Because you selected 'One', special javascript code will be executed");
// Special javascript code goes here
return;
}
else if (selectedValue == "Two") {
// Special server code gets executed on server DropDownList1_SelectedIndexChanged
__doPostBack('DropDownList1', '');
}
}
}
</script>
Source - ASPX Controls
<asp:DropDownList ID="DropDownList1" runat="server" onchange="DropDownList1_change(this)" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>-Select-</asp:ListItem>
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:DropDownList>
<br />
<!-- For some unknown reason __doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page -->
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Time of last Post Back: <asp:Label ID="Label1" runat="server"></asp:Label><br />
Time of OnSelectedIndexChanged: <asp:Label ID="Label2" runat="server"></asp:Label>
Source - Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Additional Resource - I found the following article after posting this question. Its a very old Microsoft article and the only Microsoft article I found that mentions the specific limitation of DropDowns, return values & postbacks. I haven't digged deep into their solution and not sure time will allow me to. Mainly posting it in case my solution fails down the road or doesn't work for someone else.
Intuitively you might think adding a confirm dialog box for a
DropDownList is identical to adding such a dialog box for a Button Web
control. That is, simply set the DropDownList's client-side onchange
attribute to something like: return confirm(...);. using:
DropDownListID.Attributes("onchange") = "return confirm(...);"
Unfortunately, this won't work as desired because an AutoPostBack
DropDownList's onchange attribute will be set to a bit of JavaScript
that causes a postback, namely a call to the client-side __doPostBack
function. When setting the onchange attribute programmatically
yourself, the end result is that the rendered client-side onchange
event handler has both your code and the call to __doPostBack:
The article is long so search for "Confirmation with AutoPostBack DropDownLists"
https://msdn.microsoft.com/en-us/library/aa479302.aspx
There are 2 solutions.
Solution 1:
A better work around than adding a link button surrounded by hidden span tags is to add the following to the page load event. This ensures that the function __doPostBack is available.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.GetPostBackEventReference(this, string.Empty);
}
The function __doPostBack is generated only if a control in the form needs it to perform postbacks. This includes controls like the LinkButton and other controls for which AutoPostBack is set to true. In fact, only the Button and ImageButton controls can perform postbacks without __doPostBack (see this article). For example, we can see in the HTML output that a LinkButton is rendered this way:
<a id="lnk" href="javascript:__doPostBack('lnk','')">My link</a>
Solution 2: The following approach achieves the same thing without using __doPostBack.
In the present case, you could set AutoPostBack="true" for the DropDownList:
<asp:DropDownList AutoPostBack="true" onchange="if (!confirmPostBack(this)) return false;" ... >
The onchange event handler would return false when you want to prevent the postback. The Javascript function could be something like this:
function confirmPostBack(ddl)
{
if (condition) {
...
return true;
}
else {
...
return false;
}
}
Important: The onchange event handler should not return anything to allow the postback to occur. You can use this syntax:
onchange="if (!confirmPostBack(this)) return false;"
For reasons probably explained in the article mentioned in the question, the following syntax does not work. Returning true still prevents the postback.
onchange="return confirmPostBack(this);" // Does not work!

prevent postback in js for a webform dropdown

I am developping an asp.net webform application. In a page, I have a dropdown containing some values ("a","b","c",...). When I select a value in this dropdown, a server side event is raised and I write the selected value in my DB.
This is the code :
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True"/>
protected void server_handler(object sender, EventArgs e)
{
myUpdateMethod(this.myDdl.selectedValue);
}
This is working perfectly, but now I would like to ask a confirmation on my client side when a value is selected, does we really want to update the value in my db.
If we selected yes in my confirm dialog in js, we pursue and call the server like before, if not we stop the postback. But this is what I am not able to do, I can't stop the postback, this is what i've tried :
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot(event)"/>
function confirmornot(event)
{
var str = confirm("do you want to continue?")
if (!str)// the user select no and this is where I am trying to stop to calling the server handler function. Basically there, I want here nothing to happen
{
//solution 1
event.preventDefault();
//solution 2
event.stopPropagation() or event.stopImmediatePropagation()
//solution 3
return false or return true
}
None of these solutions worked, the server side function is called whatever I put, I think that is because of my autpostback="true" on my drodown, but if I remove
this, then I will be in the opposite problem, and my server side function will never be called.
Thanks in advance for your help
You may try this:
Make ClientIDMode="Static" to asp net dropdown so that you will have static id "myDdl" and also set autopostback to false
In confirmornot method instead of return statement, try
__doPostBack('myDdl');
i Have a hacky solution for you
HTMl
Add a hidden field
<asp:HiddenField runat="server" ID="hdntocheck" />
DDL Markup
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot()"/>
Js
function confirmornot() {
if (!confirm("do you want to continue?"))
{
hdntocheck.value = "false";
}
else {
hdntocheck.value = "true";
}
}
In Cs
protected void server_handler(object sender, EventArgs e)
{
if( hdntocheck.value =="true")
{
myUpdateMethod(this.myDdl.selectedValue);
}
}

ASP.NET redirect from event handler hot by button clicked by JavaScript

I have a problem with a page not redirecting during a postback.
I have an aspx-page with this content being part of it:
<td class="tdinput" align="right">
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="verifyReleaseOtherEmployeesCase()" />
<asp:Button runat="server" ID="ButtonFrigivHidden" OnClick="ButtonFrigiv_Click"
Style="display: none;" UseSubmitBehavior="true" />
</td>
The page also contains various UpdatePanels, however the above code is not included in one.
As it is seen there's a button being displayed, which calls the following JavaScript:
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
else {
return;
}
}
So basically this JavaScript locates the 2nd button above (which is not being displayed to the user) and clicks it.
When the button is clicked the following event handler is reached on the server:
protected void ButtonFrigiv_Click(object sender, EventArgs e)
{
NyeSagerDAC.FrigivSag(SagID, LogonUser);
Response.Redirect(LastList);
}
Where LastList is a string containing the page which was the entry point for the current page (there are multiple entry points).
The server method is reached and the first line in the method is executed perfectly, however the page is not redirected.
I have done some testing regarding whether it might have been considered an AJAX-callback (which doesn't allow redirects) using the following code in the event handler:
HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
The content of the string header is empty and the Page_Load is called after the event handler is done. So I don't think this is the problem.
I have also tried to register a startup script to have the page redirect itself instead. This has been tried in various ways:
Page.ClientScript.RegisterStartupScript(GetType(),"redirect",
"window.location.href='" + LastList + "'");
And
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"window.location.href='" + LastList + "';", true);
However none of this seems to work.
The only thing I have got to work was when I removed the confirm() part of the JavaScript and had it just click the button. This resulted in the page being correctly reloaded. However, I need to ask the user actually wants to unlock another employee's task.
So I think my question is: How can I get the page to redirect? Alternatively, how can I modify the JavaScript to still ask the user to confirm and not stopping the redirect from working?
The solution is coded in .NET 4.0
Thanks in advance.
Your js function is named verifyReleaseOtherEmployeesCase but in the OnClientClick it says verifyReleaseOtherWorkersCase, assuming that is a typo you also need to prevent the first button from performing a postback.
Notice the return of false in the js function and the return in the OnClientClick
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
return false;
}
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="return verifyReleaseOtherEmployeesCase()" />

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;
}
}

RegisterClientScriptBlock ASP.net

I want to execute alert when user clicks LinkButton1.It is not working?
protected void LinkButton1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "abc", "<script language=javascript>alert(hi)</script>");
}
You mistyped the function name. Change aler to alert. Also, you forgot the delimiters around the string that you are trying to alert.
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "abc", "alert('hi');", true);
use the below
<linkButton runat="server" id="lnk1" OnClientClick="alert('hi');" />
I hope your sample doesn't have a typo, but you are calling "aler" instead of "alert"!
Also, this doesn't define that your button would run this script when the user clicks the link button, it'll be executed when the page gets loaded.
For having such behavior, you need to use the "OnClientClick" control's property, and set there the name of the function - event handler - that would do the alert.
linkButton1.OnClientClick = "myEventHandler";
And define your script in some JavaScript file or by registering a client script block during the pre-render event of your container control or page.

Categories

Resources