开发者

problem with jQuery Tokeninput and asp.net webservice

I wrote the following webservice asmx file in my website:

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

    public jsonTest () {

    }

    [WebMethod(Description = "Gets the names matching part of a title.")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void getName() {
        List<nameEntry> nameList = new List<nameEntry>();
        nameList.Add(new nameEntry() {id="1", name="John"});
        nameList.Add(new nameEntry() { id = "3", name = "Alex" });
        this.Context.Response.ContentType = "application/json; charset=utf-8";

        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(nameList);
        this.Context.Response.Write(strJSON);
    }    
}

As a start I wanted it to return the same array each time, the result of the webservice when i call it directly is:

[{"id":"1","name":"John"},{"id":"3","name":"Alex"}]

Which is the correct reply, when i use it as a local input the result is fine but when i call the webservice in the input method of tokeninput (I assigned an error message to the func开发者_开发知识库tion) i get the following error: "200 parsererror undefined"

Could anyone help me figure it out?

Thanks

Doron

EDIT: after playing around with jquery code a bit i managed to receive the data but i get the following error:

200

parsererror

[{"id":"1","name":"aaA"},{"id":"3","name":"aaA"}]{"d":null}

What I don't understand is what is d and why is it null?


You shouldn't be manually serializing that JSON and writing it out. ASP.NET will do that for you automatically if you let it:

[WebMethod(Description = "Gets the names matching part of a title.")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<nameEntry> getNames() {
    List<nameEntry> nameList = new List<nameEntry>();

    nameList.Add(new nameEntry() {id="1", name="John"});
    nameList.Add(new nameEntry() { id = "3", name = "Alex" });

    return nameList;
}

The catch is that you need to call the service a particular way with jQuery in order to get a JSON response instead of XML, specifically with a POST request of content-type application/json.


Doesn't asp.net wrap the return data in an object for security? For example, you're not getting back the array you thought you were, but instead an object {} that contains your array under the ["d"] property.

I think the plugin requires an array of objects, so you might not be able to pass the url to the tokeninput initializer. Instead, in the callback of your JSON request get the data out and into the right form (an array of objects) and then initialize the tokeninput plugin with that array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜