0

i call my server side method by jquery and from that method i am trying to access textboxes data. here is my sample code

    [WebMethod]
    public static PayPalCart CreatePayPalFields()
    {
        Page CurPage = HttpContext.Current.Handler as Page;
        string tt = ((TextBox)CurPage.FindControl("txtBillAddress1")).Text; 
    }

i am getting error for accessing the control from static method and the error message is Object reference not set to an instance of an object. then i search google to find out better solution then i got a extension method which will loop through control collection and return control if found. the code is like

public static T BetterFindControl<T>(this Control root, string id) where T : Control
{
    if (root != null)
    {
        if (root.ID == id) return root as T;

        var foundControl = (T)root.FindControl(id);
        if (foundControl != null) return foundControl;

        foreach (Control childControl in root.Controls)
        {
            foundControl = (T)BetterFindControl<T>(childControl, id);
            if (foundControl != null) return foundControl as T;

        }
    }

    return null;
}

i use the above routine also from static method like

    [WebMethod]
    public static PayPalCart CreatePayPalFields()
    {
        Page CurPage = HttpContext.Current.Handler as Page;
        string sData = CurPage.BetterFindControl<TextBox>("txtDeliveryFName").Text; 
    }

but still no luck....still getting the same error for accessing control from static method and found that the CurPage has no control. please suggest me what should i do. tell me a way out to access control from static method because method has to be static reason i am invoking that method by jquery.........need help.

Thomas
  • 33,544
  • 126
  • 357
  • 626
  • You cannot access controls from a webmethod. http://stackoverflow.com/questions/2133194/access-asp-net-control-from-static-webmethod-js-ajax-call Only during page's lifecycle an instance of `Page` (and all of it's controls) is instantiated. – Tim Schmelter Jun 06 '12 at 12:37

1 Answers1

0

You can not access the page from this ajax call, simple because the page is not exist anywhere when this call is happens.

What you can do is to send the parameters that you like to check via the ajax call, and by using javascript to get them and send them.

To say few more about what call do.

string sData = CurPage.BetterFindControl<TextBox>("txtDeliveryFName").Text;

this is a final call on the .Form post data to read what is send by control with id txtDeliveryFName. On your ajax call there is no post of the full page, and from the other hand you control what data will be post to the webmethod via javascript.

Aristos
  • 66,005
  • 16
  • 114
  • 150