locked
How I Call Master Page Method Using Jquery Ajax RRS feed

  • Question

  • User1151703306 posted

    Hi,

    I can't call [WebMethod] from Master Page using Jquery Ajax.

    I am getting the error as follows:

    GetCompletionList (forbidden)

    I have the following code in Jquery on markup of Default.aspx webpage with Master page:

        <script type="text/javascript">
            function ShowImage() {
                document.getElementById('txSearch')
                    .style.backgroundImage = 'url(/aspnet/img/snake_transparent.gif)';
    
                document.getElementById('txSearch')
                    .style.backgroundRepeat = 'no-repeat';
    
                document.getElementById('txSearch')
                    .style.backgroundPosition = 'right';
            }
    
            function HideImage() {
                document.getElementById('txSearch')
                    .style.backgroundImage = 'none';
            }
    
            $(function () {
                $("[id$=txSearch]").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: '<%=ResolveUrl("Mymasterpage.master/GetCompletionList") %>',
                            data: "{ 'prefixText': '" + request.term + "'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {
                                response($.map(data.d, function (item) {
                                    return {
                                        label: item.toString,
                                        val: item.toString
                                    }
                                }))
                            },
                            error: function (response) {
                                alert(response.responseText);
                            },
                            failure: function (response) {
                                alert(response.responseText);
                            }
                        });
                    },
                    select: function (e, i) {
                        $("[id$=hfSearch]").val(i.item.val);
                    },
                    minLength: 1
                });
            });
        </script>

    In Code Behind of Master Page Mymasterpage.master.cs I have this:

        [ScriptMethod()]
        [WebMethod]
        public static List<string> GetCompletionList(string prefixText)
        {
            using (OdbcConnection con =
                new OdbcConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString))
            {
                using (OdbcCommand com =
                    new OdbcCommand())
                {
                    com.CommandText = " SELECT ";
                    com.CommandText += "	sName ";
                    com.CommandText += " FROM ";
                    com.CommandText += "	`tbl_name` ";
                    com.CommandText += " WHERE ";
                    com.CommandText += "	sName LIKE CONCAT('%',?,'%'); ";                
    
                    com.Parameters.AddWithValue("param1", prefixText);
                    com.Connection = con;
                    con.Open();
    
                    List<string> countryNames = new List<string>();
    
                    using (OdbcDataReader sdr = com.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            countryNames.Add(sdr["sName"].ToString());
                        }
                    }
                    con.Close();
                    return countryNames;
                }
            }
        }

    Why is it so ? How to solve it ?
    Thanks

    Wednesday, May 15, 2019 11:56 AM

Answers

  • User475983607 posted

    Basic Web Forms AJAX example.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxDemo.aspx.cs" Inherits="WebFormsDemo.AjaxDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
       
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
        </form>
         <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script>
    
            $("#<%= LinkButton1.ClientID%>").click(function (e) {
                e.preventDefault();
                var data = {
                    inputParam: "Hello World"
                }
                    $.ajax({
                        type: "POST",
                        url: '/AjaxDemo.aspx/DoSomething',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                    }).done(function (data) {
                        console.log(data);
                    });
            });
        </script>
    </body>
    </html>
    
            [WebMethod]
            public static string DoSomething(string inputParam)
            {
                return $"You sent {inputParam}.";
            }

    Try setting a breakpoint and single stepping through the logic.  Open the browser's dev tools (F12) and look for any JavaScript errors.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 15, 2019 6:21 PM

All replies

  • User475983607 posted

    I can't call [WebMethod] from Master Page using Jquery Ajax.

    Correct.  Master pages do not have a URL.

    Wednesday, May 15, 2019 12:45 PM
  • User1151703306 posted

    Golia

    I can't call [WebMethod] from Master Page using Jquery Ajax.

    Correct.  Master pages do not have a URL.

    Do you mean that it is not possible?

    Wednesday, May 15, 2019 12:48 PM
  • User475983607 posted

    Do you mean that it is not possible?

    It is not possible.

    Wednesday, May 15, 2019 12:50 PM
  • User1151703306 posted

    mgebhard

    Golia

    Do you mean that it is not possible?

    It is not possible.

    Okay, thanks.

    But I have tried also on code behind Default.aspx.cs :

    [ScriptMethod()]
    [WebMethod]
    public static List<string> GetCompletionList(string prefixText)
    {
        using (OdbcConnection con =
            new OdbcConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString))
        {
            using (OdbcCommand com =
                new OdbcCommand())
            {
                com.CommandText = " SELECT ";
                com.CommandText += "    sName ";
                com.CommandText += " FROM ";
                com.CommandText += "    `tbl_name` ";
                com.CommandText += " WHERE ";
                com.CommandText += "    sName LIKE CONCAT('%',?,'%'); ";                
    
                com.Parameters.AddWithValue("param1", prefixText);
                com.Connection = con;
                con.Open();
    
                List<string> countryNames = new List<string>();
    
                using (OdbcDataReader sdr = com.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        countryNames.Add(sdr["sName"].ToString());
                    }
                }
                con.Close();
                return countryNames;
            }
        }
    }

    And in markup of Default.aspx :

    <%@ Page Title="" Language="C#" MasterPageFile="Mymasterpage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
    
    <%@ MasterType VirtualPath="Mymasterpage.master" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
        <asp:Panel ID="pnSearch" runat="server" HorizontalAlign="Center">
            <div class="pure-g">
                <div class="pure-u-1 pure-u-md-1-3">
                    <asp:TextBox ID="txSearch" runat="server"
                        BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
                    <ajaxToolkit:AutoCompleteExtender
                        ServiceMethod="GetCompletionList"
                        MinimumPrefixLength="1"
                        CompletionInterval="10"
                        EnableCaching="false"
                        CompletionSetCount="1"
                        TargetControlID="txSearch"
                        ID="AutoCompleteExtender1"
                        runat="server"
                        FirstRowSelected="false"
                        UseContextKey="True"
                        OnClientPopulating="ShowImage"
                        OnClientPopulated="HideImage">
                    </ajaxToolkit:AutoCompleteExtender>
                    <asp:HiddenField ID="hfSearch" runat="server" />
                </div>
            </div>
        </asp:Panel>
    
    <script type="text/javascript">
        function ShowImage() {
            document.getElementById('txSearch')
                .style.backgroundImage = 'url(/aspnet/img/snake_transparent.gif)';
    
            document.getElementById('txSearch')
                .style.backgroundRepeat = 'no-repeat';
    
            document.getElementById('txSearch')
                .style.backgroundPosition = 'right';
        }
    
        function HideImage() {
            document.getElementById('txSearch')
                .style.backgroundImage = 'none';
        }
    
        $(function () {
            $("[id$=txSearch]").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%=ResolveUrl("Default.aspx/GetCompletionList") %>',
                        data: "{ 'prefixText': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.toString,
                                    val: item.toString
                                }
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("[id$=hfSearch]").val(i.item.val);
                },
                minLength: 1
            });
        });
    </script>
    </asp:Content>

    I don't have error but the Search not working ....

    Wednesday, May 15, 2019 12:58 PM
  • User475983607 posted

    Basic Web Forms AJAX example.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxDemo.aspx.cs" Inherits="WebFormsDemo.AjaxDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
       
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
        </form>
         <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script>
    
            $("#<%= LinkButton1.ClientID%>").click(function (e) {
                e.preventDefault();
                var data = {
                    inputParam: "Hello World"
                }
                    $.ajax({
                        type: "POST",
                        url: '/AjaxDemo.aspx/DoSomething',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                    }).done(function (data) {
                        console.log(data);
                    });
            });
        </script>
    </body>
    </html>
    
            [WebMethod]
            public static string DoSomething(string inputParam)
            {
                return $"You sent {inputParam}.";
            }

    Try setting a breakpoint and single stepping through the logic.  Open the browser's dev tools (F12) and look for any JavaScript errors.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 15, 2019 6:21 PM
  • User1151703306 posted

    Thanks a lot Mr. mgebhard !

    Thursday, May 16, 2019 8:20 AM