0

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

  • Refer to this [answer](https://stackoverflow.com/a/8577638/7002366). In short, you can't use webmethods within your MasterPage and your should put them in a WebService or WCF Service. – FF- May 15 '19 at 15:44

2 Answers2

0

Insert the webmethod in the new web form file Default.aspx.cs and in the Default.aspx page paste this following code.

I hope I was helpful.

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
     <link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
       <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
    <script type="text/javascript">
    $(function () {
        $("#<%=Textbox1.ClientID%>").autocomplete({
            source: function (request, response) {
                var param = { prefixText: $('#<%=Textbox1.ClientID%>').val() };
                $.ajax({
                    url: "Default.aspx/GetCompletionList",
                    data: JSON.stringify(param),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest);
                    }
                });
            },
            minLength: 2 //minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data. 
        });
    });
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

        <asp:TextBox runat="server" ID="Textbox1" />
</asp:Content>
Hamamelis
  • 1,983
  • 8
  • 27
  • 41
0

try to use the Code Nugget Syntax <%: %>

for example:

Site.master.cs

public DateTime GetCurrentDate()
{
    return DateTime.Now;
}

Site.master

<script>

    function GetCurrentDate() {
        var _date = "<%: GetCurrentDate() %>";
        alert(_date);
    }

</script>

and this is the form what I use to consume a site master method

Josue Barrios
  • 440
  • 5
  • 10