Как я вызываю метод мастер-страницы, используя Jquery Ajax - PullRequest
0 голосов
/ 15 мая 2019

Я не могу позвонить [WebMethod] с Master Page, используя Jquery Ajax.

Я получаю сообщение об ошибке следующим образом:

GetCompletionList (запрещено)

У меня есть следующий код в Jquery на markup из Default.aspx веб-страница с Главная страница :

<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>

В Код позади из Мастер-страница Mymasterpage.master.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;
        }
    }
}

Почему это так?

Как это решить?

Спасибо

1 Ответ

1 голос
/ 16 мая 2019

Вставьте веб-метод в новый файл веб-формы Default.aspx.cs и на странице Default.aspx вставьте следующий код.

Надеюсь, я вам помог.

<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>
...