0

私はお問い合わせフォームに取り組んでいます。ASP.net は初めてです。お問い合わせフォームに取り組んでいる C# の中間量を知っています。値をjson配列として送信し、JSON.netで解析したいので、考えられるあらゆる方法を試して動作させました。成功しない場合は、ASMX ページから JSON を適切に送受信する方法を知る必要があります。サンプルファイルやチュートリアルはありますか? または、誰かが私が間違っていることを教えてもらえますか? これが、投稿変数を読み取る唯一の方法でした。

しかし、キーと値のペアではなく、2 つの配列だけです。

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

これが私のasmxファイルです。

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

     }

   }

ここに私のWeb設定ファイルがあります

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

3 に答える 3

4

一般的にお答えできます。上記のコードは、問題を解決しようとする試みのようです。

文字列の配列を渡すには、以下の JavaScript コードを参照してください。

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

以下に示すように、webServiceでそれを受け入れることができます

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

      }

     }

上記のコードに従えば、JSON フォーマットについて気にする必要はありません。操作のようなサービスを使用するつもりがない場合は、ページ バックで [WebMethod] を使用することをお勧めします。

文字列を渡す代わりに、ユーザー定義の JavaScript オブジェクトを渡すことができます。そのような場合は、

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

次に、以下に示すように、webService でそれを受け入れることができます。

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

または、使用するメソッドごとにクラスを作成したくない場合は、辞書を使用できます。

[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"];
          }

         }
于 2013-09-11T05:17:05.203 に答える
0

文字列として取得し、オブジェクトに逆シリアル化できます。あなたの「jsonText」を送ってください

私は自分のプロジェクトでこれを行います。FromJSONをクラスに入れて拡張機能として使うだけ ※クラスのことはしなくてもいい

例: 「{引数: ['aaa', 'bbb', 'ccc', 'ddd'], キー: ['aaa', 'bbb', 'ccc', 'ddd']}"

*System.Web.Script.Serialization を使用。

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string sendRequest(string msg)
{
    MyClass mc = FromJSON<MyClass>(msg)
    return mc.args[0];

}

class MyClass
{
    internal string[] keys;
    internal string[] args;
}

T FromJSON<T>(string json)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    T o = serializer.Deserialize<T>(json);
    return o;
}
于 2013-09-10T19:23:53.557 に答える