views:

54

answers:

3

I wrote a page Page method in my aspx page. in web service method I need to call FindControl method return textbox and get text box value. But my findControl will take MasterPage object to iterate.

Please see my code

<script type = "text/javascript">
    function ShowCurrentDateTime() {
        $.ajax({
            type: "POST",
            url: "HRDefault.aspx/GetDate",
            data: '',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function(response) {
                alert(response.d);
            }
        });
    }

    function OnSuccess(response) {  }
</script>

<System.Web.Services.WebMethod()> _
Public Shared Function GetDate() As String
    Dim txt22_2 As TextBox = CType(RenderControls.FindControlRecursive
(Page.Master, "txt22_2"), TextBox)
        Dim str As String
        str = txt22_2.Text
    Return String.Empty
End Function

But I am getting compiler error when use Page.Master:

Reference to non-shared member requires an object reference

How to pass Master Page object or Page to Page method?. So I can use in Sared method.

Is there any way I can access Textbox value directly in Page method? I need access couple of controls in Page Method.

+1  A: 

HttpContext.Current.Handler may get you the reference to page object but it will not be useful because page life cycle is not executed in PageMethods (so no view-state or request data). You have couple of alternatives:

  1. Pick control values from java-script. If needed, pass them to PageMethod using data parameter while making service call.
  2. Use Session (HttpContext.Current.Session) or cache to store data on page and then retrieve it in PageMethod. I will prefer using cache with new guid as a key and then pass guid to PageMethod.
VinayC
+1  A: 

don't know about $.ajax, but this works fine for me:

<asp:ScriptManager runat="server" EnablePageMethods="true" />
<!-- ...................... -->
<script type="text/javascript">
    function ShowCurrentDateTime() {
        x = document.getElementById('<%= TextBox1.ClientID %>').value;
        PageMethods.GetDate(x, OnSuccess, OnFailure);
    }
    function OnSuccess(response) {
        alert(response);
    }
    function OnFailure(response) {
        alert(response._message);
    }
</script>

and in code behind:

<System.Web.Services.WebMethod()> _
Public Shared Function GetDate(x as String) As String
    ' do something with x
    ' u can add more params if you need
    Return String.Empty
End Function

hope the syntax is ok, i don't remember much of vb :P

y34h
A: 

Since you're already posting data, you should be able to get reference to Request.Form collection which you can use to read posted textbox values

Rajesh Batheja