Search code examples
javascriptasp.netjqueryvb.netpagemethods

How to pass page or master page object to AJAX page method


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.


Solution

  • 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