发送键值对的JSON到ASMX服务与jquery [英] Sending Key Value Pairs as JSON to ASMX service with jquery

查看:109
本文介绍了发送键值对的JSON到ASMX服务与jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已经工作接触形式我是新来的ASP.net,我知道我是一个联系表上工作的C#中间量。我想与JSON.net发送价值观为JSON数组并解析它,我想尽一切办法,我能想到的,以得到它的工作。如果没有成功,我需要知道如何正确地发送和从ASMX网页收到JSON。是否有一个示例文件或者一个教程?或可有一个人请告诉我什么,我做错了什么?这是我能得到它的读取POST变量的唯一途径。

但它只是2阵列不是键值对。

 <!DOCTYPE HTML>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
< HEAD>
    <标题>< /标题>
    <脚本SRC =脚本/ jQuery的-2.0.3.min.js>< / SCRIPT>
< /头>
 <身体GT;
    <形式的行动=#>
        <输入类型=文本ID =名字NAME =名字值=/>
        <输入类型=文本ID =姓氏NAME =姓氏值=/>
     < /表及GT;
  < /身体GT;
  < / HTML>
 <脚本>$(文件)。就绪(函数(){    变量$连载= $('形式')serializeArray()。
    VAR字符串化= JSON.stringify($序列化);    变种键= ['姓名','姓氏'];
    VAR名单= [$('#姓名)VAL(),$('#姓')VAL()。]    VAR jsonText = JSON.stringify({ARGS:列表中,钥匙:钥匙});    $阿贾克斯({        网址:validation.asmx / sendRequest将
        方法:POST,
        数据类型:JSON
        数据:jsonText,
        缓存:假的,
        过程数据:真实,
        的contentType:应用/ JSON的;字符集= UTF-8
    })。完成(功能(数据){        的console.log(数据);    });});< / SCRIPT>

下面是我的ASMX文件,

 使用系统;
    使用System.Collections.Generic;
    使用System.Linq的;
    使用的System.Web;
    使用System.Web.Services;
    使用Newtonsoft.Json;
    使用System.Web.Script.Services;
    使用System.Data这;    [WebService的空间(namespace =htt​​p://tempuri.org/)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)    [System.Web.Script.Services.ScriptService]
     公共类验证:System.Web.Services.WebService {        公共验证(){       //取消注释以下行,如果使用设计的组件
       //的InitializeComponent();
    }    [的WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公共字符串sendRequest将(列表<串GT;指定参数时,列表与LT;字符串>键)
    {       VAR ARG = ARGS;
       VAR键=键;       返回ARGS [0];     }   }

这是我的web配置文件

 <?XML版本=1.0&GT?;
<结构>
  <&的System.Web GT;
     <编译调试=真targetFramework =4.5/>
      <的httpRuntime targetFramework =4.5/>
       <&Web服务GT;
           <&协议GT;
             <添加名称=HTTPGET/>
             <添加名称=HttpPost/>
           < /协议>
       < / WebServices的>
    < /system.web>
  < /结构>


解决方案

我一般可以回答你。以上code似乎是你试图解决这个问题。

要传递一个String数组见下文

给出的JavaScript code

  VAR MyStringArray =新的Array();
    MyStringArray.push(firstval);
    MyStringArray.push(secondval);
VAR StringifiedContent = JSON.stringify('的varName':MyStringArray);
        $阿贾克斯({
                键入:POST,
                网址:validation.asmx / sendRequest将,//路径web服务
                数据:StringifiedContent,
                的contentType:应用/ JSON的;字符集= UTF-8,
                数据类型:JSON
                成功:函数(MSG){
                }
            });

您可以接受它的web服务如下图所示。

  [的WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公共字符串sendRequest将(列表<串GT;的varName)//变量名称必须相同
    {
      的foreach(在varName的VAR eachvals)
      {      }     }

您不必理会JSON格式,如果你按照code如上图所示。如果你不打算使用像操作的服务,然后在页面回用[的WebMethod]将是一个更好的选择。

不是传递字符串,你可以通过一个用户自定义JavaScript对象。在这种情况下,这将是,<​​/ P>

  VAR MyStringArray =新的Array();
   VAR为MyObject = {};
   MyObject.Key =123;
   MyObject.Value =ABC;
    MyStringArray.push(为MyObject);VAR StringifiedContent = JSON.stringify('的varName':MyStringArray);
        $阿贾克斯({
                键入:POST,
                网址:validation.asmx / sendRequest将,//路径web服务
                数据:StringifiedContent,
                的contentType:应用/ JSON的;字符集= UTF-8,
                数据类型:JSON
                成功:函数(MSG){
                }
            });

然后,你能接受它的web服务如下图所示。

  [的WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公共字符串sendRequest将(列表&LT;&MyObject的GT;的varName)//变量名称必须相同
    {
      的foreach(在varName的VAR eachvals)
      {
      字符串KEYVAL = eachvals.Key;
      字符串值= eachvals.Value;
      }     }
公共类为MyObject
{
公共字符串键{获取;集};
公共字符串值{获得;设置;}
}

另外,如果你不想为每个使用,你可以使用字典方法创建类。

  [的WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)
        公共字符串sendRequest将(词典&LT;字符串,字符串&GT;的varName)//变量名称必须相同
        {
          的foreach(在varName的VAR eachvals)
          {
          。字符串KEYVAL = eachvals [钥匙];
          字符串值= eachvals [值]。
          }         }

I have a been working on a contact form I am new to ASP.net, I know an intermediate amount of C# I am working on a contact form. I want to send the Values as a json array and parse it with JSON.net, I tried every way I could think of to get it to work. Without success, I need to know how to properly send and receive JSON from an ASMX page. Is there an Example file or maybe a tutorial? Or can some one please tell me what I am doing wrong? This was the only way I could get it to read the post vars.

But Its just 2 arrays not key value pairs.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-2.0.3.min.js"></script>
</head>
 <body>
    <form action="#">
        <input type="text" id="firstname" name="firstname" value=""/>
        <input type="text" id="lastname" name="lastname" value=""/>
     </form>
  </body>
  </html>
 <script>

$(document).ready(function () {

    var $serialize = $('form').serializeArray();
    var stringify = JSON.stringify($serialize);

    var keys = ['firstname', 'lastname'];
    var list = [$('#firstname').val(), $('#lastname').val()];

    var jsonText = JSON.stringify({ args: list, keys: keys });

    $.ajax({

        url: "validation.asmx/sendRequest",
        method: "POST",
        dataType: "json",
        data:jsonText,
        cache: false,
        processData: true,
        contentType: "application/json; charset=utf-8"
    }).done(function (data) {

        console.log(data);

    });

});

</script>

Here is my asmx file,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using Newtonsoft.Json;
    using System.Web.Script.Services;
    using System.Data;

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

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

        public validation () {

       //Uncomment the following line if using designed components 
       //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string sendRequest(List<string> args, List<string> keys)
    {

       var arg = args;
       var key = keys;

       return args[0];

     }

   }

here is my web config file

<?xml version="1.0"?>
<configuration>
  <system.web>
     <compilation debug="true" targetFramework="4.5"/>
      <httpRuntime targetFramework="4.5"/>
       <webServices>
           <protocols>
             <add name="HttpGet"/>
             <add name="HttpPost"/>
           </protocols>
       </webServices>
    </system.web>
  </configuration>

解决方案

I can Answer you generally. The above code seems to be your attempt to solve the problem.

To pass an Array of string see the javascript code given below

    var MyStringArray = new Array();
    MyStringArray.push("firstval");
    MyStringArray.push("secondval");
var StringifiedContent = JSON.stringify('varName':MyStringArray);
        $.ajax({
                type: "POST",
                url: "validation.asmx/sendRequest",//Path to webservice
                data: StringifiedContent,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                }
            }); 

You can Accept It in the webService as shown below

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string sendRequest(List<string> varName)//The variable name must be same
    {
      foreach(var eachvals in varName)
      {

      }

     }

You don't have to bother about JSON formatting if you follow the code as shown above. If you don't intend to use a service like operation then using [WebMethod] in page back will be a better option.

Instead of passing string you can pass a userdefined javaScript object. In such case it would be,

var MyStringArray = new Array();
   var MyObject = {};
   MyObject.Key="123";
   MyObject.Value="abc";
    MyStringArray.push(MyObject);

var StringifiedContent = JSON.stringify('varName':MyStringArray);
        $.ajax({
                type: "POST",
                url: "validation.asmx/sendRequest",//Path to webservice
                data: StringifiedContent,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                }
            }); 

Then, You can Accept It in the webService as shown below

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string sendRequest(List<MyObject> varName)//The variable name must be same
    {
      foreach(var eachvals in varName)
      {
      string Keyval =eachvals.Key;
      string Value =eachvals.Value;
      }

     }
public class MyObject 
{
public string Key {get;set};
public string Value {get;set;}
}

Alternatively, if you don't want to create classes for each method that use, you can use dictionaries.

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string sendRequest(Dictionary<string,string> varName)//The variable name must be same
        {
          foreach(var eachvals in varName)
          {
          string Keyval =eachvals.["Key"];
          string Value =eachvals.["Value"];
          }

         }

这篇关于发送键值对的JSON到ASMX服务与jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆