vote up 1 vote down star

Hello,

I've been working on this for 3 hours and have given up. i am simply trying to send data to an asp.net web method, using jQuery. The data is basically a bunch of key/value pairs. so i've tried to create an array and adding the pairs to that array.

My WebMethod(aspx.cs) looks like this (this may be wrong for what i'm building in javascript, i just dont know):

   [WebMethod]
    public static string SaveRecord(List<object> items)
    .....

Here is my sample javascript:

var items = new Array;

    var data1 = { compId: "1", formId: "531" };
    var data2 = { compId: "2", formId: "77" };
    var data3 = { compId: "3", formId: "99" };
    var data4 = { status: "2", statusId: "8" };
    var data5 = { name: "Value", value: "myValue" };

    items[0] = data1;
    items[1] = data2;
    items[2] = data3;
    items[3] = data4;
    items[4] = data5;
Here is my jQuery ajax call:

var options = {
        error: function(msg) {
            alert(msg.d);
        },
        type: "POST",
        url: "PackageList.aspx/SaveRecord",
        data: { 'items': items },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(response) {
            var results = response.d;
        }
    };
    jQuery.ajax(options);

i get the error -Invalid JSON primitive: items.-

so...if i do this:

var DTO = { 'items': items };

and set the data parameter like this:

data: JSON.stringify(DTO)

then i get this error:

Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027

I've been going in circles for hours. someone please help my small brain figure this out.

thanks a ton.

flag

68% accept rate
Change your web method to accept a plain old Object, then take a look at exactly what the object is, and cast and process it in the web method. – Cory Larson Jul 18 at 2:01
Question though, you're using webmethods, but not using the JavaScript proxy class that is generated automatically for you? – Cory Larson Jul 18 at 2:02
thanks Cory, i did initially change hte web method to accept a plain object, which helped me figure out what to expect. thanks! – dwfresh Jul 20 at 4:21

4 Answers

vote up -1 vote down check

When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can debug and see what type of object the web method in is recieving.

You need to convert your object to a string when using jQuery

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CustomEquip.WebForm1" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="~/js/jquery.js" />
            </Scripts>
        </asp:ScriptManager>
        <div></div>
    </form>
</body>
</html>
<script type="text/javascript" language="javascript">
    var items = [{ compId: "1", formId: "531" },
        { compId: "2", formId: "77" },
        { compId: "3", formId: "99" },
        { status: "2", statusId: "8" },
        { name: "Value", value: "myValue"}];

        //Using Ajax.Net Method
        PageMethods.SubmitItems(items,
            function(response) { var results = response.d; },
            function(msg) { alert(msg.d) },
            null);

        //using jQuery ajax Method
        var options = { error: function(msg) { alert(msg.d); },
                        type: "POST", url: "WebForm1.aspx/SubmitItems",
                        data: {"items":items.toString()}, // array to string fixes it *
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: false, 
                        success: function(response) { var results = response.d; } }; 
        jQuery.ajax(options);
</script>

And the Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomEquip
{
    [ScriptService]
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static void SubmitItems(object items)
        {
            //break point here
            List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
        }
    }
}
link|flag
Kenneth, i just tried the jquery version exactly as you coded it above and still got the error: Invalid JSON primitive: items. "Message":"Invalid JSON primitive: item.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ..... something is still wrong with that array, but can't figure it out! – dwfresh Jul 20 at 2:41
Kenneth, I tried your PageMethods version and this worked fine. Thanks very much. I may just go this route if i can't figure out the jQuery solution. much appreciated. – dwfresh Jul 20 at 2:53
vote up 5 vote down

In your example, it should work if your data parameter is:

data: "{'items':" + JSON.stringify(items) + "}"

Keep in mind that you need to send a JSON string to ASP.NET AJAX. If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead.

It looks like you've read it already, but take another look at my example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX. It covers everything you need to make this work.

Note: You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else). It automatically does this for you, based on the specified types of the parameters to your method. If you find yourself doing that, you are doing it wrong.

link|flag
vote up 0 vote down

Decorate your [WebMethod] with another attribute:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

I believe this is in System.Web.Services.Scripting...

link|flag
1  
I think the problem is not that server is not able to send JSON to the client, problem is about server not able to de-serialize the incoming JSON. – SolutionYogi Jul 17 at 23:38
vote up 0 vote down

see link http://www.andrewrowland.com/article/display/consume-dot-net-web-service-with-jquery

This is the wonderfull example i haven't see earlier. If u like then please mail me.

Thanks.

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.