【问题标题】:how to get the posted data in c#如何在c#中获取发布的数据
【发布时间】:2012-08-08 01:34:05
【问题描述】:

我在我的应用程序中使用 ajax,我必须使用 $.post 方法。

通常,发送到服务器的数据是键值对。我可以让他们通过:

HttpContext.Current.Request.QueryPara['name'];
....

但在某些情况下,要发送到服务器的数据不包含名称。

它只是一个 xml 段。

像这样:

var data='<data>xxxxx<data>';
$.post('http://server/service.asmx/test',data,function(){
  //callback
},'xml');

那我怎样才能在我的 webmethod 中获取数据呢?

【问题讨论】:

    标签: asp.net post webmethod


    【解决方案1】:

    您应该必须使用 'json' dataType 将数据传递给 web 方法。

    看看样本:

    Service.asmx


    [ScriptService]
    [WebService(Namespace = "http://localhost/testapp/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Service : System.Web.Services.WebService{
       [WebMethod]
       public int Square(int no){ return no * no;}
    }
    

    和 JavaScript 代码来请求这个 webmethod

    <script type="text/javascript">
    $(function () {
        $("#button1").click(function () {
            $.ajax({
                type: "post",
                url: "service.asmx/Square",
                data: "{no: 10}",
                dataType: "json",
                contentType: "application/json",
                success: function (data) {
                    alert("Result :" + data.d);
                },
                error: function (src,type,msg) {
                    alert(msg); //open JavaScript console for detailed exception cause
                }
            });
        });
    });
    </script>
    
    <body>
      <input type="button" id="button1" value="Square" />
    </body>
    

    【讨论】:

    • 我的意思是在服务器端获取数据
    【解决方案2】:

    我不确定 asp.net 是否可以做到这一点。但您始终可以提供这样的名称:

    var data= { data: '<data>xxxxx<data>'};
    $.post('http://server/service.asmx/test',data,function(){
      //callback
    },'xml');
    

    然后在服务器上你就可以通过

    var data = Request.Params("data");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多