Showing posts with label JSON. Show all posts
Showing posts with label JSON. 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.