i use jquery to create clone dropdownlist everytime add button clicked. For some reason, i have to do the validation checking inside the save event function. Once there is error, a alert message will pop and stop the function. After that, the clone objects will disappear due to the postback. Is there anyway to prevent it disappear or any others way to stop the postback after the alert message.
*Noted: the validation checking must do inside save event function for some reason.
You can return false from the javascript function to stop postback
HTML
<asp:button id="btnSave" runat="server" onclickclick="return validation();" />
Javascript
function validation()
{
//validation code
return false;
}
If you want to get the object created on client using javascript then you will need to put the information in some hidden field and using that information to create server control on postback. You can use [asp.net ajax UpdatePanel1 for simple and straight forwards solution.
Related
I have a webforms page with a gridview and several other buttons. In debugging, I've noticed all the binding to gridview executes during postback in the Page_Load sub. Only after this is all done do the click handler(s) get invoked and in my case the handler does a Response.Redirect to another page.
So, I found this on SO: Run the button event handler before page_load.
It suggests the possibility of detecting the target of the postback during page_load and I was thinking of exiting the page_load in this case and letting the button click handler load a new page (i.e. avoiding all the wasted building and formatting of the gridview.
Here is a snippet from my Page_Load:
If IsPostBack Then
Dim targetOfPostBack As String = Request.Params("__EVENTTARGET").ToString()
End If
During PostBack the __EVENTTARGET is always an empty string rather than something suggesting the "add" button I clicked (i.e. ctl00$MainContentPlaceHolder$btnAddEvent). Trapped here:
The OP on SO above is expressing this same approach in C# while my implementation is VB.Net. What am I doing wrong?
On your asp button try setting UseSubmitBehavior="False"
Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.
When the UseSubmitBehavior property is false, control developers can use the GetPostBackEventReference method to return the client postback event for the Button. The string returned by the GetPostBackEventReference method contains the text of the client-side function call and can be inserted into a client-side event handler.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior(v=vs.110).aspx
You can write a client side script to redirect the page thus avoiding the postback all together. Set "OnClientClick" (Asp.NET Button) or "OnClick" (HTML Buttom) property and then simply return false.
Eg:
Script:
function RedirectToURL()
try {
window.open("<Your URL Here>", "_self", "menubar=0,resizable=
} catch (e) {
}
return flase;
}
Button :
<input type="button" id="btnToggleConfig" onclick="RedirectToURL()" runat="server"
value="Click here to Goto Link" />
This is the ASP.NET page life cycle at work: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx
A few options:
check out this post for _EVENTTARGET being empty:
__EVENTTARGET is empty on postback of button click
Handle the redirect on the client side (if possible)
Only fill the gridview only once on page_load (If Not IsPostback) if that's an option
If you're only worried about the gridview being recreated and eating up some 'processing power' or time, depending on size, users, etc, may not be a big issue, so could leave as-is.
This is probably a simple question.
I use ASP.NET ajax toolkit and Jquery. I want to call a server-side function/method from Javascript and have it update a control. Can i do this?
Client-side
send_request(foobar,args);
Server-side
private void foorbar(){
Label1.Text = "updated";
}
Do you want it to fire a server-side method and update a server-side control on the page? You can create a ASP.NET UpdatePanel, let's say there is a button1 inside, and from your JQuery code, write this.
function OnClick()
{
__doPostBack(button1.ClientID, "argument")
}
and in your server side code, Page_Load event, you will find the EVENTTARGET and EVENTARGUMENT in the REQUEST variable, which contains the information you just postback, you can then update the control in the UpdatePanel itself as long as the control is within the UpdatePanel, it will be handled properly by ASP.NET AJAX.
More details here
http://www.dotnetspider.com/resources/16920-Post-back-gets-demystified-doPostBack-defined.aspx
Yes that can be done Client Callback
You could take a look at ASP.NET Page Methods.
jQuery.ajax({
url:'url to call', //usually webservices in asp.net
dataType:'json',
type:'POST', //(asp.net werbservices by default accepts POST request only)
success:function(data){
//do some thing with this data, like will dom elements etc
}
});
#smkngspcmn:
I placed everything inside an update panel and did something like $('#Year').change(function() { __doPostBack("submit", ""); }); That does do a full post back without Ajax. What am i doing wrong? Should i place the above script inside the update panel as well?
The first argument to __doPostBack() should be the UniqueID of a server-side control inside the UpdatePanel. For example, you can put a hidden button inside the UpdatePanel:
<asp:Button ID="HiddenButton" runat="server"
style="display:none" OnClick="HiddenButton_Click" />
When the button is rendered on the page, you can take the name attribute of the <input type="submit"> element that represents the submit button and use it for the first argument to _doPostBack(). In this way, whenever your script runs it the UpdatePanel will make an asynchronous postback and the HiddenButton_Click event handler will be fired.
I have a composite User control for entering dates:
The CustomValidator will include server sided validation code. I would like the error message to be cleared via client sided script if the user alters teh date value in any way. To do this, I included the following code to hook up the two drop downs and the year text box to the validation control:
<script type="text/javascript">
ValidatorHookupControlID("<%= ddlMonth.ClientID%>", document.getElementById("<%= CustomValidator1.ClientID%>"));
ValidatorHookupControlID("<%= ddlDate.ClientID%>", document.getElementById("<%= CustomValidator1.ClientID%>"));
ValidatorHookupControlID("<%= txtYear.ClientID%>", document.getElementById("<%= CustomValidator1.ClientID%>"));
</script>
However, I would also like the Validation error to be cleared when the user clicks the clear button. When the user clicks the Clear button, the other 3 controls are reset. To avoid a Post back, the Clear button is a regular HTML button with an OnClick event that resets the 3 controls. Unfortunately, the ValidatorHookupControlID method does not seem to work on HTML controls, so I thought to change the HTML Button to an ASP button and to Hookup to that control instead. However, I cannot seem to eliminate the Postback functionality associated by default with the ASP button control. I tried to set the UseSubmitBehavior to False, but it still submits. I tried to return false in my btnClear_OnClick client code, but the code sent to the browser included a DoPostback call after my call.
btnClear.Attributes.Add("onClick", "btnClear_OnClick();")
Instead of adding OnClick code, I tried overwriting it, but the DoPostBack code was still included in the final code that was sent to the browser.
What do I have to do to get the Clear button to clear the CustomValidator error when clicked and avoid a postback?
btnClear.Attributes.Item("onClick") = "btnClear_OnClick();"
Try adding a return false; at the end of your onClick call. That should prevent the default behavior (in this case submit).
btnClear.Attributes.Add("onClick", "btnClear_OnClick(); return false;")
Are you wanting to clear the error message on the client side if they fix the error without having to click on anything right?
I did something like this if I have your issue right but calling a revalidation function that called some client side javascript code and then hides the span that the error message is in if they fixed the issue.
See my blog article and let me know if this is what you are wanting to solve. The part you want to read is towards the bottom.
http://coding.infoconex.com/post/ASPNET-CustomValidator-that-validates-multiple-controls-using-both-Server-Side-and-Client-Side-scripting.aspx
I am using JQuery to toggle the visibility of a in a webforms application. I am using an update panel to suppress the postback when my is clicked. What I would like to do when this is clicked is call the JQuery code that I use to toggle the once the postback has completed. What code(client-side or server-side) do I need to implement? Thanks you.
Edit:
I don't just need to fire the toggle event when the postback has completed, but when server-side code says that the user's input is valid.
you can try this on server side:
if(<input is valid>)
{
ScriptManager.RegisterStartupScript(this.Page,this.Page.GetType(),"Toggle", "your javascript function call", true);
}
this will call your function when the postback completes
Sure:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
This is a JavaScRipt callback. Just plug you handler in to toggle your code
I have a few controls that inherit from ASP.NET buttons and use onserverclick.
If the user clicks twice, the button fires two server side events. How can I prevent this?
I tried setting this.disabled='true' after the click (in the onclick attribute) via javascript, but that blocks the first postback as well.
See this example for disabling control on postback. It should help you do what you're trying to achieve.
http://encosia.com/2007/04/17/disable-a-button-control-during-postback/
You don't necessarily want to show the button disabled on postback. You want to make sure they don't accidentally submit twice. So disabling or hiding the button as a result of a server-side action is already too late in the game. By this point the 2nd request is already on it's way. You need to either do it with javascript or make sure your server side code won't run twice.
In case of an updatepanel and a button inside a FormView-Template I use the following approach:
// Using that prm reference, hook _initializeRequest
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequestBuchung);
// Abfangen von Mehrfachklicks auf Buttons für asynchrone Postbacks im Updatepanel
function InitializeRequestBuchung(sender, args) {
var arrButtonIds = ["ButtonInsert", "ButtonUpdate"];
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & jQuery.inArray(args.get_postBackElement().id, arrButtonIds) > -1) {
args.set_cancel(true);
}
}
This cancels the following postback if an async postback is currently still active. Works perfectly.
Someone else said this somewhere on here a few days ago, and I concur - use javascript to simply hide the button instead of disabling it; you could show a "spinner" image in its place, which lets the user know what is going on.
Instead of hiding, what I have done is swapping buttons using javascript. Show another greyed out image on the click of the first button.
Set the Button property UseSubmitBehavior to false. Then create an OnClientClick function that disables the button.
It would look something like this:
<script type="text/javascript">
function disableFunctn(button){
button.disabled = true;
}
</script>
<asp:Button ID="button1" UseSubmitBehavior="false" OnClientClick="disableFunctn(this);"/>
fastest cheapest way:
<asp:Button ID="button1" UseSubmitBehavior="false" OnClientClick="this.disabled=true;"/>
You can also try for example btnSave.Enable = false; when the button is hit and before the processing for the button is done in the Click Event routine. If you need it to be reset to allow it to be enabled have a separate button that resets the button for reuse.
Another method is to set the button with verification so that the user is asked if they want to Save, it should pop up both times.
Yet another method would be to flag the first occurrence then set a popup for the second to verify a second or subsequent usage.