Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Thursday, October 20, 2011

Calling a web method that defined in user control

Scenario:
I have an usercontrol on my page and I want to call a webmethod using jquery ajax on usercontrol’s button click. I got that call is not able to get the specified url in the ajax request.

Reason:
You can't call a page method declared within an ASCX user control.

Solutions:
1. You should use an ASMX web service.  They are almost exactly the same as a page method, both when writing them and when consuming them.

2. Create method on user control containing page and do work on the data passed through json. 

UserControlContainingPage:

namespace Demo{
public partial class UserControlContainingPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(EnableSession = true)]
public static string Control_GetTest()
{
return Control.GetTest();
}
}}

MyUserControl.ascx.cs

namespace Demo{
public partial class MyUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.Session["test"] = DateTime.Now.ToString();
}
// ALMOST A WEB METHOD
public static string GetTest()
{
return " is " + HttpContext.Current.Session["test"];
}
}}

Control.ascx

<script type="text/javascript">   
var dataSend = {};
$.ajax({
type: "POST",
url: "UserControlContainingPage.aspx/Control_GetTest",
data: dataSend,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(data) {
alert("before");
},
success: function(data) {
alert("Page Load Time from Session " + data.d);
},
fail: function() {
alert("fail");
}
}); </script>

So you have one ASPX which acts basically like a Interface for all AJAX Methods in all your Web Controls.

Wednesday, October 19, 2011

Passing JSON parameters through jQuery

If you’re sending data in your request, use jQuery’s contentType parameter to set the content-type, so that the default is never added:

$.ajax({
type: "POST",
url: "WebService.asmx/WebMethodName",
data: "{'fname':’developer’, 'lname':’rocks’}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

ASP.NET AJAX script services and page methods understand and expect input parameters to be serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.

However, if you directly provide a JSON object as the data parameter for an $.ajax call, jQuery will attempt to URL encode the object instead of passing it on to your web service.

Take this sample request, for example:

$.ajax({
type: "POST",
url: "WebService.asmx/WebMethodName",
data: {'fname':’developer’, 'lname':’rocks’},
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Because that data parameter is a valid object literal, calling the web service this way won’t throw any JavaScript errors on the client-side.

You can send it as:

fname=dave&lname=ward

To which, the server will respond with:

Invalid JSON primitive: fname.

This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter, like this:

$.ajax({
type: "POST",
url: "WebService.asmx/WebMethodName",
data: "{'fname':’developer’, 'lname':’rocks’}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

It’s a small change in syntax, but makes all the difference. Now, jQuery will leave our JSON object alone and pass the entire string to ASP.NET for parsing on the server side.

Taking these three caveats into account, I think this is the best practice for calling read-only ASP.NET AJAX web services via jQuery:

$.ajax({
type: "POST",
url: "ServiceName.asmx/WebMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do interesting things here.
}
});

When consuming web services that require parameters, the usage is similar. Just make sure that you’re passing a JSON object in a string:
$.ajax({
type: "POST",
url: "ServiceName.asmx/WebMethodName",
data: "{'fname':’developer’,'lname':’rocks’}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do magic here.
}
});
In either of these cases, substitute PageName.aspx for ServiceName.asmx and PageMethodName for WebMethodName if you want to call a page method instead of a web service.

Monday, April 11, 2011

AJAX

Ajax the acronym stands for Asynchronous JavaScript and XML. Here's a curveball: Ajax doesn't
have to use XML, and neither does it have to be asynchronous. Ajax applications can use XML,
and they can be updated asynchronously. These are quite common tricks and techniques used
to update the page, but they are not tied to these technologies.

Partial Post back
we send specified information to server and according to this information we get response.
for example:
we have country and states drop down list. if we select country then states dropdown list will
be filled according the country.
This is done by JavaScript but we do not know JavaScript. In .Net we have Ajax controls. when
their event fire then these control's value sent to the server and fetched data manipulated.
we need to code in Jscript. these control generate Jscript code and assigned to the browser.
To Implement Ajax:
First add Script Manager control.
->to do partial post back here is control Update Panel.
->Now add control to page in the Update Panel
A Small Example of this:
* Add Scrip Manager and UpdatePanel Control to your page
* Add a label and button in UpdatePanel
* Add a label and button on Page outside of Update Panel

protected void btnUpdatePanelButton_Click(object sender, EventArgs e)
    {
        lblUpdatePanelLabel.Text = DateTime.Now.ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        lblWebFormButton.Text = DateTime.Now.ToString();
     
    }
when you click on btnWebFormButton then it will post back and then display date etc., but 
when you click on btnUpdatePanelButton then page will not past back; only these controls
information will be send to the server for the changes.
run it and look and check the difference..
one more thing..
put these buttons code at form Load event.. and check the behavior of these controls.
Script Manager generates the JavaScript events etc. for the controls which are in update panel.
Synchronous Post Back
by default  case post back is synchronous post back.
Asynchronous Post Back 
if your control is of the Update Panel and want to implement Ajax on this control's particular
event, it is done by Asynchronous Post Back.
To do this open properties of Update Panel and there is property named Triggers.
* Here you can specify particular control name and event of the control on which asynchronous
   post back take place.

protected void btnUpdatePanelButton_Click(object sender, EventArgs e)
    {
        lblUpdatePanelLabel.Text = DateTime.Now.ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //lblWebFormButton.Text = DateTime.Now.ToString();
        lblUpdatePanelLabel.Text = "Asynchronous PostBack";
    }
Things to remember:
* control's whose information to fetch partially must be in UpdatePanel
* Event of Control's that fire could be inside the UpdatePanel or outside the Update Panel.
* If Control is out of the UpdatePanel and implementing Ajax for control outside the Update Panel
Called Asynchronous Partial Post Back.