Json.net: How can I return a JObject from [WebMethod]?

I am testing json.net . I would like to use its linq-to-json syntax to return json from a function attributed to [WebMethod], but I am getting errors.

For example, if I use code

[WebMethod, ScriptMethod(UseHttpGet = true)]
public static JObject GetStuff() {
    return new JProperty("string", "value");
}

Called by the following javascript:

  PageMethods.GetStuff(/* parameters */, function(data) {
      // do stuff with data
  });

I get the error "Unable to access child value in Newtonsoft.Json.Linq.JValue."

What should I return to ensure that my javascript data object is populated with JSON?

+3
source share
1 answer

Why not just return objects and port JSON serialization to the underlying infrastructure:

public class MyModel
{
    public string Value { get; set; }
}

and in your web method:

[WebMethod, ScriptMethod(UseHttpGet = true)]
public static MyModel GetStuff() {
    return new MyModel {
        Value = "some value"
    };
}
+1
source

Source: https://habr.com/ru/post/1785181/


All Articles