Convert array to JSON and pass it to asmx

I am trying to use JSON.stringify()

(from json2.js from json [dot] org) to convert a JavaScript array to a JSON string and pass it to an asmx web method. I am using jQuery AJAX.

The call reaches the web method where I take the List <Object>

as parameter , but I get an empty list in debug mode.

My JSON string looks well formed with all the data, I even tried using single quotes and double quotes (escaped) around the JSON string "names". Please, help.

+2


a source to share


3 answers


[WebMethod]
public void SomeMethod(List<object> param)
{
 ....
}

      

Will accept a JSON string that looks like this:

'{"param": ["xx", "zz", "yy"]}'

      



So try something like this:

var data = JSON.stringify({param: myarray});

      

+5


a source


http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

This link helped me because I wanted to use the model to input json data.



As a side note, I tried to use $ .post (...) but had no luck until I split it into a $ .ajax call and specified the content type.

0


a source


I found a solution to your problem

Prashiddha.com.np solution

            <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            <html xmlns="http://www.w3.org/1999/xhtml">
            <head runat="server">
            <title></title>

            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
            <script type="text/javascript">
                var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
                $(document).ready(function() {
                    $('#txtAutoSuggest').keyup(function() {
                    var str = $("#txtAutoSuggest").val();
                    var a = JSON.stringify({ name: str });
                    CallService(a);
                });
            });

            function CallService(a) {
            $.ajax({
                type: "POST",
                url: url,
                data: a,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, status) {
                $('#lblResult').text(data.d);
            },
            error: Error
            });
            }

            function Error(request, status, error) {
                $('#lblResult').text("Not Matched");
            }
            </script>
            </head>
            <body>
            <form id="form1" runat="server">
            <div>
            <asp:TextBox ID="txtAutoSuggest" runat="server"></asp:TextBox>
            <asp:Label ID="lblResult" Text=" " Width="100%" runat="server" />
            </div>
            </form>
            </body>
            </html>

      

0


a source







All Articles