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.