I was wondering. I tried googling for answers but they don't give me answers. Thanks.
Yes, an ASP.NET AJAX Page Method will continue execution after a user leaves a page, but the result (if any) will not come back to the page, since the page where the request was initiated is now gone.
For example:
Code-behind on Default.aspx page:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetHelloWorld()
{
Thread.Sleep(20000);
return "Hello World";
}
protected void ButtonContactRedirect_OnClick(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
}
Markup on Default.aspx page:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetHelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
});
</script>
<asp:Button runat="server" ID="ButtonContactRedirect" Text="Go to Contacts Page" OnClick="ButtonContactRedirect_OnClick"/>
So we have a button on Default.aspx that will redirect to another page (Contacts.aspx) when the user clicks it. Meanwhile, when Default.aspx is loaded, there is an AJAX call to the page method that sleeps for 20 seconds before returning the string Hello World.
If you put a break point on the following line:
return "Hello World";
When you run the program and the page loads, if you do not click the button for 20 seconds then the AJAX success callback will fire and an alert will show the string object returned. If you press the button before the 20 second sleep finishes, then the Redirect() will happen and the Contacts.aspx page will load, but the break point will be hit once the sleep finishes; however the returned Hello World string will be lost, because the AJAX context was tied to the Default.aspx page and not the Contacts.aspx page, which is now gone.
Related
Is it possible to call a c# webmethod on mouseover on Linkbutton ? what i want is to call a webmethod in which i am binding a repeater control with datatable. How?
in aspx:
<asp:LinkButton Text='<%#Eval("SNA")%>' ID="lnkpro1" runat="server"
CssClass="linkbutton" servicemethod="GetRecords"
OnClick="btn_Click1" CommandArgument='<%# Eval("Sets") %>'></asp:LinkButton>
in aspx.cs:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public void GetRecords(object sender, EventArgs e)
{
}
I am not getting the point that is how is it possible to call a webmethod on linkbutton mouseover. I have used a webmethod in textbox autocomplete extender but it has a propperty of calling a webmethod but is it so in this case also? Thank you.
Use ASP.NET AJAX Page Methods, like this:
[WebMethod]
public static List<Record> GetRecords()
{
// Go to database to get list of records
List<Record> listOfRecords = GetRecordsFromDatabase();
return listOfRecords;
}
I made up the Record class here. A list of something needs to be returned, so I made it up for the example's sake.
Note: ASP.NET AJAX Page Methods automatically JSON-encode their response, so there is no need for serialization in the page method if you are using JSON on the client-side.
Now you can call the ASP.NET AJAX Page Method, like this:
$(document).ready(function() {
$('.linkbutton').mouseover(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetRecords",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Do something with records returned here
// Use result.d to get to JSON data
}
});
});
});
You can do that using jQuery Ajax method to call a WebMethod:
Refer this for an ultimate example for Calling an ASP.NET C# WebMethod
I have a method on a page marked as a [WebMethod] that uses some session state as part of its operation. After I wrote this code, I suddenly had a flash of memory that you need to use EnableSessionState when you use session state in a [WebMethod] (e.g. see here: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx). But it seems to be working fine. Why?
Sample code behind:
protected void Page_Load(object sender, EventArgs args) {
this.Session["variable"] = "hey there";
}
[System.Web.Services.WebMethod]
public static string GetSessionVariable() {
return (string)HttpContext.Current.Session["variable"];
}
Sample body html:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getSession() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetSessionVariable',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.getElementById("showSessionVariable").innerHTML = msg.d;
}
});
return false;
}
</script>
<form id="form1" runat="server">
<div id="showSessionVariable"></div>
<button onclick='return getSession()'>Get Session Variable</button>
</form>
On http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx, you will see that this applies to XML Web services (i.e., classes derived from System.Web.Services.WebService).
[WebMethod(EnableSession=true)]
Because your page presumably extends System.Web.UI.Page, it is not necessary to explicitly enable the session. On http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx, you can see that EnableSessionState is enabled by default for Pages (which you probably already know).
http://forums.asp.net/t/1630792.aspx/1
Answer of gsndotnet:
You are right but whatever you are saying is applicable to a method in context of WebServices. We also use same WebMethod attribute on the methods of a WebService (.asmx). So in context of Web Services when we want to allow the access to Session we have to add EnableSession = true. Whereas in context of PageMethods they already have access to Session as they are defined inside a class that inherits from Page class.
Your msdn link means that you use web service, i.e. class derived from System.Web.Services.WebService.
In your code you add your method directly on page, so it has access to session.
i am a beginner
function PopupUserRegist() {
result = $.ajax({ url: "Default.aspx?cmd=Setting",
async: false ,
complete: function () {
// unblock when remote call returns
}
}).responseText; ;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request["cmd"] == "Setting")
{
div.InnerText = "test"; //This does not change inner text
}
}
protected void Button2_Click(object sender, EventArgs e)
{
div.InnerText = "test";//This change inner text
}
when call PopupUserRegist(); does not change?
You've got confused about the flow of control with ASP.NET.
Page_Load() occurs on the server side at page generation time and can change the data that is about to be sent back in the HTML page to the browser.
When you call the ASPX again through ajax() from JavaScript, the codebehind can't directly touch the page content, because that's already sitting over on the browser. If you want to change the data in the page, you'll have to have the ASPX return a plain value to the JavaScript code in the responseText:
$('#myDiv').text(
$.ajax({
url: 'Default.aspx?cmd=Setting',
async: false
}).responseText
);
or, better, avoiding the unpleasant use of synchronous xmlhttprequest:
$.get('Default.aspx?cmd=Setting', function(result) {
$('#myDiv').text(result);
});
If you really want to blur the line between code that runs on the client and server sides, look at using runat="server", click events, postbacks and viewstates.
Check if the condition is met.
i am a beginner
function PopupUserRegist() {
result = $.ajax({ url: "Default.aspx?cmd=Setting",
async: false ,
complete: function () {
// unblock when remote call returns
}
}).responseText; ;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request["cmd"] == "Setting")
{
div.InnerText = "test"; //This does not change inner text
}
}
protected void Button2_Click(object sender, EventArgs e)
{
div.InnerText = "test";//This change inner text
}
when call PopupUserRegist(); does not change?
You've got confused about the flow of control with ASP.NET.
Page_Load() occurs on the server side at page generation time and can change the data that is about to be sent back in the HTML page to the browser.
When you call the ASPX again through ajax() from JavaScript, the codebehind can't directly touch the page content, because that's already sitting over on the browser. If you want to change the data in the page, you'll have to have the ASPX return a plain value to the JavaScript code in the responseText:
$('#myDiv').text(
$.ajax({
url: 'Default.aspx?cmd=Setting',
async: false
}).responseText
);
or, better, avoiding the unpleasant use of synchronous xmlhttprequest:
$.get('Default.aspx?cmd=Setting', function(result) {
$('#myDiv').text(result);
});
If you really want to blur the line between code that runs on the client and server sides, look at using runat="server", click events, postbacks and viewstates.
Check if the condition is met.
I have a gridview inside an updatepanel and I have a javascript that calls a page method using jquery. I'd like the page method to refresh the gridview based on the parameter it receives from the ajax call.
So far, I have the following:
1) in the javascript, there's a function that calls the page method:
function GetNewDate(thedateitem) {
DateString = (valid json date format that works)
$.ajax({
type: "POST",
url: "./CallHistory.aspx/ResetDate",
contentType: "application/json; charset=utf-8",
data: DateString,
dataType: "json",
success: successFn,
error: errorFn
})
};
2) In the aspx page I have:
<asp:UpdatePanel ID="MyPanel" runat="server">
<ContentTemplate>
<asp:GridView ID="MyGrid">
3) In the code behind:
public partial class Pages_CallHistory : System.Web.UI.Page
{
List<ViewCallHistoryModel> TheCallHistory;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TheDate = new DateTime(2011, 1, 13);
LoadCallHistory(TheDate);
MyGrid.Datasource = TheCallHistory;
MyGrid.Databind;
}
}
protected void LoadCallHistory(DateTime TheDate)
{
linq query that fills the variable TheCallHistory
}
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
var test = new Pages_CallHistory();
var test2 = test.LoadCallHistory(TheNewDate.Date);
//test2 loads fine
test.GridCallHistory.DataSource = test2;
//this is not underlined but bugs at runtime
//Object reference not set to an instance of an object.
test.GridCallHistory.DataBind();
test.MyPanel.Update();
//this is not underlined but doesn't get executed because
//because it stops at the line above
//I'd like to update the content of
//the gridview on the page with the updated gridview.
}
What I'd like to do in the page method is 1) call LoadCallHistory with the new date parameter and 2) tell the gridview MyGrid to rebind with the new data that's in TheCallHistory.
I'm struggling with this page method; it's not working and I'm stuck. How is this done?
ok so the solution is to use _doPostBack in javascript:
__doPostBack('MyPanel', DateString);
The page method is for sending and receiving data only, not for doing postbacks on updatepanels.
Take a look at my answer to this related question here. In short, you create a new instance of the grid and capture its output manually.