Обратная передача JSON в веб-метод С# добавляет буквальный контроль

Я узнаю о веб-методах и отправляю им сообщения с помощью JSON, у меня есть следующее ниже, но он говорит, что не может найти веб-метод (404). Не вижу, где я ошибаюсь, спасибо.

В javascript страницы:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
       <script type="text/javascript">
           $(document).ready(function () {
               $(".FilterResults").click(function () {
                   var topic = $(".DropDownList1").val();
                   var number = $(".DropDownList2").val();
                   var month = $(".DropDownList3").val();
                   $.ajax({
                       type: "POST",
                       url: "filterresultshold.asmx/filterresults",
                       data: "{'args': '" + topic + "'}",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       success: function (msg) {
                           // If you return something from the method, it can be accessed via msg.d                
                       }
                   });

                   // To prevent the postback
                   return false;
               });
           });
</script> 

В ascx:

<form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"><asp:Literal ID="Literal1" Text="Text to display" mode="PassThrough" runat="server" /></asp:PlaceHolder>
        <asp:DropDownList ID="DropDownList1" class="DropDownList1" runat="server"></asp:DropDownList>
        <asp:DropDownList ID="DropDownList2" class="DropDownList2" runat="server"></asp:DropDownList>
        <asp:DropDownList ID="DropDownList3" class="DropDownList3" runat="server"></asp:DropDownList>
        <asp:Button ID="FilterResults" class="FilterResults" runat="server" Text="Fill DropDownList" />
    </div>
</form>

В коде позади:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for filterresults
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class filterresultshold : System.Web.Services.WebService {

    [System.Web.Services.WebMethod]
    public void filterresults(string args)
    {
        string[] data = args.Trim().Split(',');
        string topic = data[0];
        string number = data[1];
        string month = data[2];
        string control = "<umbraco:Macro alias='pdfarchivelist' runat='server' topic='" + topic + "' number='" + number + "' month='" + month + "'></umbraco:Macro>";
        //LiteralControl literal = new LiteralControl(control);
        //PlaceHolder PlaceHolder1 = new PlaceHolder();
        //PlaceHolder1.Controls.Add(literal);
    }

}

Затем в коде .ascx позади:

public partial class usercontrols_pdfarea : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {      
        if (!Page.IsPostBack)
        {
            // Populate Drops
            var rootNode = uQuery.GetRootNode();
            DropDownList1.Items.Add(new ListItem("SELEZIONA NUMERO"));
            DropDownList2.Items.Add(new ListItem("SELEZIONA MESE"));
            DropDownList3.Items.Add(new ListItem("SELEZIONA ARGOMENTO"));

            //display the password on the Gallery Folder in the media area
            var startMedia = uQuery.GetMediaByName("pdfs").FirstOrDefault();
            var DropList = rootNode.GetDescendantNodes().Where(x => x.NodeTypeAlias == "File");

            foreach (var item in startMedia.Children)
            {
                DropDownList1.Items.Add(new ListItem(item.getProperty("number").Value.ToString())); //NUMBER
                DropDownList2.Items.Add(new ListItem(item.getProperty("month").Value.ToString())); //MONTH
            }

            foreach (var item in startMedia.Children.Select(p => p.GetPropertyAsString("topic")).Distinct().ToList())
            {
                DropDownList3.Items.Add(new ListItem(item.ToString()));
            }
        }
    }
}

person PeteTheGreek    schedule 01.11.2012    source источник
comment
Вы добавляете контроль через службу?   -  person शेखर    schedule 01.11.2012
comment
Написан ли ваш метод filterresults в коде ascx? Я думаю, вам нужно написать веб-метод в коде aspx позади.   -  person Jith    schedule 01.11.2012
comment
Можете ли вы получить ответ (ошибка или что-то другое) при переходе по URL-адресу?   -  person markpsmith    schedule 01.11.2012
comment
Я обновил его, чтобы использовать веб-службу, поместил код веб-метода в файл веб-службы и обновил javascript, чтобы указать на него, но получил внутреннюю ошибку службы 500.   -  person PeteTheGreek    schedule 01.11.2012


Ответы (4)


// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class filterresultshold : System.Web.Services.WebService {

Просто сделайте то, что предложено в комментарии

Кстати, filterresults не должно быть статичным

person Yuriy Rozhovetskiy    schedule 01.11.2012

для получения вашего веб-метода вы используете этот код

$.ajax({
                   type: "POST",
                   url: "Default.aspx/filterresults",
                   data: "{'args': '" + topic + "'}",
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   success: function (msg) {
                       // If you return something from the method, it can be accessed via msg.d                
                   }
               });

я думаю, вы должны немного измениться, как это

$.ajax({
                   type: "POST",
                   url: "Default.aspx/filterresults",
                   data: '{args:"' + topic + '"}',
                   contentType: "application/json; charset=utf-8",
                   dataType: 'json',
                   success: function (msg) {
                       // If you return something from the method, it can be accessed via msg.d                
                   }

я думаю, это поможет вам..... });

person Rajpurohit    schedule 01.11.2012

если ваш скрипт находится во вложенной папке, вам нужно использовать абсолютный путь:

url: "/filterresults.asmx/filterresults",
person Carlos Martinez T    schedule 01.11.2012

если ваш файл сценария находится в той же папке, что и файл filterresults.asmx, то ваш URL-адрес в порядке, но если нет, вам нужно указать правильный путь, например, абсолютный путь, как показано ниже:

url: "/services/filterresults.asmx/filterresults",

Вам также необходимо определить веб-службу как службу сценария, чтобы разрешить вызовы ajax, как показано ниже:

[System.Web.Script.Services.ScriptService]
public class filterresultshold : System.Web.Services.WebService

И удалите ключевое слово static из своего веб-метода. Затем добавьте в свой веб-метод следующее:

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = 
    System.Web.Script.Services.ResponseFormat.Json)]
public string filterresults(string args)

Наконец убедитесь, что у вас есть следующие элементы в вашем web.config в разделе, который сообщает веб-сервисам прослушивать вызовы Http Post:

<system.web>
<webServices>
  <protocols>
    <add name="HttpPost"/>
    <add name="HttpGet"/>
  </protocols>
</webServices>
</system.web>

Удачи!

person Ashkan    schedule 01.11.2012
comment
спасибо, приближаюсь, я все еще получаю внутреннюю ошибку сервера 500, думаю, это может быть неправильная передача значений раскрывающегося списка, я попробовал var topic = $(#‹%= DropDownList1.ClientID %›).val(); но я получаю имя «DropDownList1» не существует в текущем контексте. - person PeteTheGreek; 01.11.2012
comment
Нажмите F12, если вы используете FireBug, установленный в вашем Firefox, или если вы используете Chrome, и в разделе Net --› XHR --› Post посмотрите, какой запрос отправлен. - person Ashkan; 01.11.2012
comment
спасибо, я получаю сообщение Не удалось создать тип 'filterresults'. в System.Web.UI.SimpleWebHandlerParser.GetType (String typeName) ошибка - person PeteTheGreek; 01.11.2012
comment
Вы раскомментировали [System.Web.Script.Services.ScriptService] в верхней части класса веб-сервиса? - person Ashkan; 01.11.2012
comment
Вам нужно объявить службу веб-методов в web.config или диспетчере сценариев ascx или что-то в этом роде? - person PeteTheGreek; 01.11.2012
comment
Смотрите обновленный ответ. Я думаю, вам нужно сказать, что веб-служба должна прослушивать вызовы HTTP Post в вашем файле asp.net web.config. - person Ashkan; 01.11.2012
comment
Я все еще получаю сообщение об ошибке «Нет веб-службы: /filterresultshold.asmx», хм. - person PeteTheGreek; 01.11.2012