I have several small divs which are utilizing jQuery draggable. These divs are placed in an UpdatePanel, and on dragstop I use the _doPostBack() JavaScript function, where I extract necessary information from the page's form.
My problem is that when I call this function, the whole page is re-loaded, but I only want the update panel to be re-loaded.
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET receives argument 1 of __doPostBack
__EVENTARGUMENT receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
What if I don't know the ID of the control whose click handler I want to run?
If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
This will inject the unique id of the control into the javascript, should you wish it
Per Phairoh: Use this in the Page/Component just in case the panel name changes
<script type="text/javascript">
<!--
//must be global to be called by ExternalInterface
function JSFunction() {
__doPostBack('<%= myUpdatePanel.ClientID %>', '');
}
-->
</script>
Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference
(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)
Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):
function RefreshGrid() {
<%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.
Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.
__doPostBack(UpdatePanelClientID, '**Some String**');
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?
Related
I implemented a dynamic enable/disable function in a page thanks to a javascript function calling a backing java bean method that sets to true/false a boolean, which is then used to disable (or not) a primefaces commandLink button.
Everything works fine, but I wanted to know if instead of changing the appearance of the button when is it disabled, I could keep the regular appearance (and even better, printing an alert message when trying to click it without having to render another web element).
Here are the simplified pieces of code:
Javascript function:
function enableSubmit(){
jQuery(element).click(function(){
if (condition){
rc_enable();
} else {
rc_disable();
}
});
}
And the primefaces commandButton together with the remoteCommands:
<p:remoteCommand name="rc_disable" update="submitButton" actionListener="#{mappenBean.setDisabled}" />
<p:remoteCommand name="rc_enable" update="submitButton" actionListener="#{mappenBean.setEnabled}" />
<h:commandLink id="submitButton" action="#{mappenBean.updateFund}" styleClass="FormButton" rendered="#{!sitzungBean.gedruckt}" disabled="#{!mappenBean.enabled}">
...[action listeners etc.]
<h:outputText value="Eingaben übernehmen" />
</h:commandLink>
The java bean functions simply set the boolean to true or false.
It seems that I cannot implement a javascript click() function to display an alert if the disabled button is clicked, because once disabled it is not recognized anymore.
The primefaces version is 2.2.1 (i know...) and JSF is 2.1
Any help will be welcome, thanks a lot!
you can add css class to the button to be disabled and disable mouse events
.disabled-button{
pointer-events: none;
}
it wont change the appearance but it will do the trick
You can put a validate function (client side) to check if the condition is true/false and then show the message or submit the action.
First remove the disabled="#{!mappenBean.enabled}"
The button will be always enable. But it will not be submitted if the condition is false.
Add an onclick="return validate();" to your commandLink
Create a javascript function and a dialog for the message.
<script type= "text/javascript">
function validate(){
if(condition){
dialogMessage.show(); // or an alert
return true;
}else{
return false;
}
</script>
Your xhtml will be something like this:
<h:commandLink id="submitButton" action="#{mappenBean.updateFund}" styleClass="FormButton" rendered="#{!sitzungBean.gedruckt}" onclick="return validate();" >
...[action listeners etc.]
<h:outputText value="Eingaben übernehmen" />
</h:commandLink>
I finally managed to do so by adding a click handler on the commandLink with the following code:
onclick="if(#{!mappenBean.enabled}) {alert('test'); return false;}"
However, as Kukeltje pointed out:
But keep in mind that this is a fake and insecure way of disabling. People with a browser developer tool can easily circumvent this. There is a very good and valid reason JSF does all this serverside (never trust the client). It might better be done the other way around. Disable it server side and via css 'enable' it visually and clickable client side!!!
I will keep it running that way for now as it was urgent and I will try and implement the right way of doing it.
Thanks a lot to everyone for your help!
I apologize if this has been answered somewhere but I could not find my particular problem's answer.
I have a asp object:
<asp:CheckBox ID="chkRemove" runat="server" Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>' OnCheckedChanged
= "OnCheckedChanged_CommonWord" AutoPostBack="true" />
Basically I want to show a message box asking if its ok to remove, if no or cancel is selected, don't do a postback (or don't run any server side code), and if yes then run that function "OnCheckedChanged_CommonWord".
I tried doing a javascript Confirm() call which pops up but if I press yes, the C# server side code does not run ("OnCheckedChanged_CommonWord") the "no" or "cancel" works perfectly as it doesn't do a postback.
P.s. Please no AJAX due to server restrictions for me.
The Checkbox control actually lacks any type of OnClientCheckChanged event that can be used to manage if a PostBack should occur or not (like OnClientClick, etc.) based on a client-side event.
But you should be able to accomplish this using an onclick attribute with a function to manage the default PostBack by calling it manually :
<asp:CheckBox ID="chkRemove" runat="server"
Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>'
OnCheckedChanged="OnCheckedChanged_CommonWord"
AutoPostBack="true"
onclick='return OnClientCheckChanged("Are you sure you want to do this?",this);' />
<script>
function OnClientCheckChanged(prompt,source) {
if (confirm(prompt)){
__doPostBack("'" + source.id + "'", '');
return true;
}
else {
return false;
}
}
</script>
When the CheckBox is actually clicked, it will trigger your confirm() prompt and based on the result, it will either trigger an explicit PostBack (via the nasty __doPostBack() call or it won't do anything.
I'm not a huge fan of the __doPostBack() call, but it seems like an appropriate solution here.
NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)
<asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.
I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.
How can I avoid the page reload ?
P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.
Thanks in advance :)
You need to use return statement at two points.
OnClientClick="return jsfunction();"
function jsfunction()
{
//
return false;
}
OR, you can return false after the function call like this.
OnClientClick="jsfunction(); return false;"
Note if you want to do postback conditionally then you need to return true or false.
OnClientClick="return jsfunction();"
function jsfunction()
{
if(conditionForPostBack)
return true;
else
return false;
}
or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type
<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
But with this code it will not fire server side event "OnClick"
if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .
<button id='btn_1' onclick='ajax_function()'>Button</button>
html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.
Searching for the same thing as you i find a patch:
If you call a method server side, you can use AJAX with the update panel, but that didn't worked for me. But you can save what you want in Session, so you have it as far as Session lasts.
// Save at SessionParameter the elementToSave we want.
this.Session["SessionParameter"] = elementToSave;
// Retrieve the info from the Session
ElementYouNeededToSave = (TypeOfTheElement)Session["SessionParameter"];
Hope this will help someone in my situation.
I have a simple form (textbox, submit button) which is wrapped in an update panel.
<asp:UpdatePanel ID="ReplyUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Textbox id="ReplyTextBox" runat="server"/>
<asp:Button id="SubmitButton" OnClick="SubmitButton_Click" runat="server"/>
<ContentTemplate>
</asp:UpdatePanel>
So, when i click the button, the server-side click event is fired (SubmitButton_Click), stuff happens to the db, and the page is re-rendered (asynchronously).
Here's my issue - i need to execute some JavaScript after all the "stuff happens to the db".
In other words, i need to create some JavaScript whose data/parameters are based on server-side logic.
I've tried this:
Page.RegisterStartupScript
and this
ScriptManager.RegisterStartupScript
Neither work (nothing happens).
Now i now i can hook into the .add_pageLoaded function using the client-side AJAX libary (to execute client-side scripts once partial update is complete), but the problem is i need data from the server that is created on the button click event.
Ie:
Sys.Application.add_init(function () {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function (sender, args) {
var panels = args.get_panelsUpdated();
for (var i = 0; i < panels.length; i++) {
// check panels[i].id and do something
}
});
});
The only "hack" i can think of at the moment is to do the above, but call a web service, getting all the data again then executing my script. I say "hack" because i shouldnt need to do an asynchronous postback, hook into the after-partial-postback event handler then call the server again just to get the info that was previously posted.
Seems like a common problem. And no, i cannot remove the UpdatePanel (even though i would love to), don't want to waste time arguing why.
Any non-hacky ideas?
EDIT
Clarification on the data i need sent to script:
I type some text in the textbox, click submit, then the server creates a database record and returns an object, which has properties like ID, Name, URL, Blah, etc. These are the values that the script requires.
So if i were to call a web service from the client-code, in order to get the values that were just created, i would need to do some hacks (get last record modified that has the value of the textbox). Not ideal, and neither is two AJAX calls for one form post. (update panel postback, then web service call).
Instead of add_pageLoaded you'll want add_endRequest here, like this:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
//check here...
});
The difference is that endRequest runs when any partial postback comes back.
I am running into an issue with running javascript from an external javascript file inside of an UpdatePanel. I am trying to get a color picker working inside of a ListView. The ListView is inside of an UpdatePanel.
I am using this color picker.
Here is what I have narrowed it down to:
If I use the color picker on a textbox outside of an UpdatePanel, it works perfectly fine through all postbacks.
If I use the color picker on a textbox inside of an UpdatePanel, it works, until I do an async postback(clicking on an "EDIT" button in the ListView). Once the UpdatePanel has done the postback, the textbox will no longer show the color picker when clicked. The same occurs when the textbox is in either the InsertItemTemplate or EditItemTemplate of the ListView.
If you would like to replicate it, simply download the color picker(it's free), then add this to a webpage...
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="panel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" ID="textbox" CssClass="color" />
<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
When the page loads, the color picker works fine. When you click on the button(which does a postback), the color picker will no longer work.
Any ideas?
After an asynchronous roundtrip, any startup scripts will not be run, which is likely why it doesn't work after the AJAX callback. The color picker likely has functions which need to be executed on page load.
I've run into this so many times that I wrote a small method to register my scripts in the code-behind, which handles both async and non-async round trips. Here's the basic outline:
private void RegisterClientStartupScript(string scriptKey, string scriptText)
{
ScriptManager sManager = ScriptManager.GetCurrent(this.Page);
if (sManager != null && sManager.IsInAsyncPostBack)
{
//if a MS AJAX request, use the Scriptmanager class
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), scriptKey, scriptText, true);
}
else
{
//if a standard postback, use the standard ClientScript method
scriptText = string.Concat("Sys.Application.add_load(function(){", scriptText, "});");
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), scriptKey, scriptText, true);
}
}
I actually baked the above into a base page class so that any page I'm working with can call this.RegisterClientStartupScript(...). To do that, simply create a base page class and include it there (making sure to mark protected not private or your inheriting page classes won't be able access it).
With the above code, I can confidently register client scripts regardless of whether the page is doing a postback or callback. Realizing you are using external script files, you could probably modify the above method to register external scripts rather than inline. Consult the ScriptManager class for more details, as there are several script registering methods...
After looking at the jscolor source code, I noticed that it initializes everything on window load. So, you will probably need to re-init with something like this (inside the UpdatePanel):
function yourInit(){
/* keep in mind that the jscolor.js file has no way to determine
that the script has already been initialized, and you may end
up initializing it twice, unless you remove jscolor.install();
*/
if (typeof(jscolor) !== 'undefined'){
jscolor.init();
}
}
if (typeof(Sys) !== 'undefined'){
Sys.UI.DomEvent.addHandler(window, "load", yourInit);
}
else{
// no ASP.NET AJAX, use your favorite event
// attachment method here
}
If you decide to put the jscolor script inside the UpdatePanel, you will also need to add something like this to the end of the jscolor.js:
if(Sys && Sys.Application){
Sys.Application.notifyScriptLoaded();
}
Have you tried ScriptManager.RegisterStartupScript which allows you to "adding JavaScript from the server to a page when performing an asynchronous postback" ?
I would guess that the jscolor.js code which runs to setup the color picker is only being called when your page first loads, so when the control is regenerated on the server, you lose the changes jscolor made. Could you register some javascript to be called in your code behind so that it would call the init method on jscolor when your asynch call completed?