0

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>
Jesse
  • 785
  • 2
  • 9
  • 29
  • there is no sendanonymous method in the asmx page. Give only the required code in the question – Subin Jacob Sep 10 '13 at 05:27
  • OK I will update it. when you use the jquery serializeArray() – Jesse Sep 10 '13 at 19:02
  • OK I will update it. when you use the jquery serializeArray() you get [{name:"firstname", value:""}, {name:"lastname", value:""}] how do i send that to my asmx page and parse it? I tried using JSON.stringify like so in my code but the WebMethod won't take it as an argument. Thats why I ended up using the 2 arrays, how do I get it to recieve the var stringify?? – Jesse Sep 10 '13 at 19:17

3 Answers3

4

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

         }
Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
0

You can get it as a string and deserialize it to the object. send your "jsonText"

I do this in my project. I just put the FromJSON in a class and use it as extension *You don't have to do the class thing

Example: "{args: ['aaa', 'bbb', 'ccc', 'ddd'], keys: ['aaa', 'bbb', 'ccc', 'ddd']}"

*using 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;
}
Sahelanthropus
  • 164
  • 1
  • 4
  • 13
0

The standard KevValuePair class of the .NET Framework won't work, simply because the setters are private.

I've seen in your code that you're not a newbie on this, so just create a small class with public getter/setter and you're good to go.

[Serializable]
public class MyKVP
{
    public string k { get; set; }

    public string v { get; set; }
}

Now in your web method, your signature should change to this:

public string sendRequest(MyKVP[] args);

And your JavaScript code will need this change:

var kvps = [
    {k:'firstname', v: $('#firstname').val()},
    {k:'lastname', v: $('#lastname').val()} ];

var jsonText = JSON.stringify({ args: kvps });
Adrian Salazar
  • 5,279
  • 34
  • 51
  • I just learned ASP.net a few days ago I am not really as big of a fan of the the whole controllers setup, I am still working on that I want to learn more ASP.net. I didn't want to separate the key value pairs initially but I could not get it to work so I did it the way I posted above. I actually do Coldfusion Development and javascript, I got the hang of this relatively quickly because I used to build apps in Flash Actionscript 2 and 3. I wanted to actually take the JSON and convert it to a Hashtable or DataSet originally. – Jesse Sep 11 '13 at 03:54
  • You have the problem of strong typed C# methods. So I suggest you to send your JSON as a string parameter, so ASP sees only a string. Then use in the server-side JSON-NET to do the de-serialization for you. See this post http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – Adrian Salazar Sep 11 '13 at 08:55