Use asp.net AJAX from javascript - asp.net

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.

Related

Detecting target of postback early in page_load to exit so click handler can run

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.

TextBox keydown event at server side in asp.net

i have a textbox on a page, now whenever any age number is entered in that page, that page should be loaded in my datalist, i have created rest of the thing, but i am not getting how to trigger the textbox onkeydown event from asp.net, i know working with that from javascript, but the problem is i have below things done in that function:
it applies the currentpage value to the static variable from textbox
it binds the datalist
it enable disable the next previous buttons accordingly
and i dont think this i can do from javascript, anyone have any resolution, how this could be achieved from server side, onkeydown event
You can capture the keydown event in a javascript function then do a AJAX call to the server. If this does not suit you, then you could try manually do postback in javascript.
So in your textbox:
mytextBox.Attributes.Add("onkeydown", "return doDataListBind()");
Now in the javascript function:
function doDataListBind()
{
__doPostBack("myTextBox"); // etc, etc
// some other code here...
}
More info can be found here:
http://geekswithblogs.net/mnf/archive/2005/11/04/59081.aspx
http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/
Try looking into or using either:
AJAX Control Toolkit, or
JQuery Autocomplete Plugin
Alternatively you could try to call _postback() function from a client side event/function for your textbox in javascript

ASP.NET button click fire jQuery

I have a jQuery Pager control, for each page there is a set of textboxes and a submit button. When this submit button is clicked I want it to fire off some jQuery to update the controls on the front end (i.e. current page, set visibility of controls etc). The button is an asp.net web forms postback button.
Does anyone know any way of doing this?
Merry Christmas!
Inject js from code-behind after your postback success like:
string script = "$(function(){setPage(\"" + yourpagenumber+ "\");});";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Pager", script, true);
And in the js you will have a setPage function that does the job of setting page with your jquery pager plugin.
function setPage(pagenumber){
alert(pagenumber);
//do your page setting here
}
Note: you can use Page.ClientScript.RegisterStartupScript if that fits your needs but the idea remains same.
Don't use a submit button, use an input of type button with an onclick event instead.
Use the OnClientClick attribute of the asp:button i.e.
OnClientClick="JQueryFunction();return false;"
for no postback and
OnClientClick="JQueryFunction();return true;"
for a postback. I'm assuming that that JQueryFunction() returns true.

Display ASP.NET Control on Event

I'm looking to create a custom date picker with code examples from several sources.
Is the code to display/hide an ASP.NET control when a user clicks a button usually done with JavaScript or ASP.NET code? By display/hide, I mean within the page not a popup window.
Please provide a simple example. (If ASP.NET, VB example preferred over C#)
The answer is, it depends. Do you want the date picker show/hide to trigger a postback and thus some code on the server, or do you want it to act purely on the client?
If you want it to act purely on the client, then, modify the markup for your button:
<asp:Button runat="server" ID="myButton" OnClientClick="ShowHideCalendar()" Text="myButton" />
<script language="javascript" type="text/javascript">
var calendarVisible = false;
function ShowHideCalendar()
{
if (calendarVisible)
{
// Code to *SHOW* calendar here
// Show the DIV it's contained in, pop the window with it in, etc..
}
else
{
// Code to *HIDE* the calendar here
}
}
</script>
The key bit is the "OnClientClick" property of the asp:Button control.
Its best practice to do such thing asynchronously, rather than having a full postback that refreshs the entire page.
That means that you have two options:
Update an UpdatePanel in which your
control is placed. That gives you
the benefit of only re-rendering the
content in the UpdatePanel.
Use
clientside scripts to toggle the
control. You also need to perform a
callback, that tells your codebehind
that you just toggled the visibility
to asure your code is in the same
state as the webpage displaying it.
I'd prefer using the second one.

Calling Javascript form a ASP.NET Button located inside of an Update Panel

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

Resources