JSON postback to c# webmethod add literal control

泪湿孤枕 提交于 2019-12-12 13:42:22

问题


I'm learning about webmethods and posting back to them using JSON, I've got the following below, but it says it can't find the webmethod (404). Can't see where I'm going wrong, thanks.

In the page 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> 

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

In the code behind:

    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);
    }

}

Then in the .ascx code behind:

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()));
            }
        }
    }
}

回答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 {

Just do what suggested in comment

BTW, the filterresults shouldn't be static




回答2:


for get your web method you use this code

$.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                
                   }
               });

i think you should little bit changes like this

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

i think this will help you..... });




回答3:


if your script is located in a subfolder, you need to use an absolute path:

url: "/filterresults.asmx/filterresults",



回答4:


if you script file is located in the same folder as filterresults.asmx file, then you url is ok, but if not, you need to write the correct path e.g an absolute path like below:

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

You also need to define your webservice as a script service to allow ajax calls, like below:

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

And remove the static keyword from your webmethod. Then add the following on your web method:

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

Finally make sure you have following elements in your web.config in section that tells webservices to listen to the Http Post calls:

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

Good Luck!



来源:https://stackoverflow.com/questions/13175652/json-postback-to-c-sharp-webmethod-add-literal-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!