json webservice asp.net 2.0

Im trying to get a page talking to a webservice through jquery.

this is the jquery:

function Test(item) {
  $.ajax({
    type: "POST",
    url: "WebService.asmx/test",
    data: '{' +
                    'Item:"' + item + '"' +
               '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        var data = jQuery.parseJSON(msg);
        if (!data.error) {
            alert("YES!!");
        }
        else {
            alert("Error" + " " + data.error);
        }
    },
    error: function (msg) {
        alert('Get Details Failure: ' + msg);
    }
 });
};

This is the web service:

    using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {}

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string Test(string Item)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(Item);
        return strJSON;
    }
    }

but i get his error:

System.InvalidOperationException: Request format is invalid: application/json; charset=utf-8.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

why???

Answers


 data: '{' +
                    'Item:"' + item + '"' +
               '}',

needs to be:

data: JSON.stringify({Item: item}),

that will produce:

'{"Item": "item's value"}'

That is valid json. You were missing the " around Item


In addition:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string Test(string Item)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    string strJSON = js.Serialize(Item);
    return strJSON;
}

should be:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test(string Item)
{
    return Item;
}

You don't need to serialize that string.


Your JSON doesn't look valid to me. Values and keys should be surrounded by quotations, like this:

'{ "Item" : "' + item + '" }'

EDIT; Maybe something to do with your web.config. Check out this persons solution.


Seems to be a malformed JSON string.

Alse you might want to have a look at this free library for parsing / writing JSON in .NET !

NewtonSoft's JSON Library for .NET

It's quite simple to use, offers a lot of methods and you won't have to rely on Javascript parser.


As the other answers have stated, you have some JSON issues.

First off, you're using a JSONSerializer in your web service for your return value - but if you're just using a string, there's no reason to use the JSONSerializer. I'm assuming you're doing more than that, so I have an example at the bottom that may simulate what you're trying to do.

Second, you're trying to parse your return value in your JavaScript even though the JSONSerializer wraps your JSON object inside another object ("d") when it serializes it. So what you want to deserialize in your JavaScript is msg.d, not just msg. Once you do that, you'll get the underlying object literal.

I enhanced the service logic a bit just to get some different results based upon what is sent in. But I think if you handle your JSON appropriately, knowing the JSONSerializer sticks your object inside another, you'll be good to go.

EXAMPLE

default.htm

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript">
    $(document).ready(function () {
        Test('stuff');
        Test('balh');
    });

    function Test(item) {
        var item = { Item: item };
        $.ajax({
            type: "POST",
            url: "WebService.asmx/Test",
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var data = JSON.parse(msg.d);
                alert(data);
                if (!data.error) {
                    alert("YES!!");
                }
                else {
                    alert("Error" + " " + data.error);
                }
            },
            error: function (msg) {
                alert('Get Details Failure: ' + msg);
            }
        });
    };
</script>

WebService.asmx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        public WebService() { }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string Test(string Item)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();

            string strJSON;
            if (Item=="stuff")
            {
                var returnValue = new { Item = "stuff", success = true };
                strJSON = js.Serialize(returnValue);
            }
            else
            {
                var returnValue = new { Item = "boo", error = true };
                strJSON = js.Serialize(returnValue);
            }

            return strJSON;
        }
    }
}

Let me describe what I got from your questions.

  1. You want to have webservice method something like public string HelloWorld(string name) where name is your input from the asp page and some string say Hello Gud Morning Mr XYZ is the returned to the asp page.

  2. You want to use JSON format for data interchange between the view and the webservice.

  3. You want to use the JQUERY AJAX for achieving the requirements,

Then I am here with the answer.

Click her for details

WebService

       <%@ WebService Language="C#" %>
        using System;
        using System.Data;
        using System.Data.SqlClient;
        using System.Configuration;
        using System.Web;
        using System.Web.Services;
        using System.Web.Services.Protocols;
        using System.Collections;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;

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

        // To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.

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

        [WebMethod]
            public string HelloWorld(string name)
            {
                Utility ut = new Utility();  // some class where you will have your database connection
                ArrayList suggestedProblemName = ut.getItems(name);  // some method of the class
            return ""+suggestedProblemName[0];
            }
        }

Need Your Help

Create Alert Dialog inside of Handler

android multithreading

I want to create an alert dialog from a handler which gets signaled when a thread terminates this is my code which causes:

Losing copy/paste shortcut-keys on web page with ActiveX control

internet-explorer activex shortcut-key

Short: I think I need to know how an ActiveX control does/should interact with (shortcut) key presses when it is on a page in Internet Explorer?