WebMethod returning JSON but the response obj in my $.ajax() callback is only a string

前端 未结 1 1718
情书的邮戳
情书的邮戳 2020-12-14 13:37

Here is my home-made Serializing class:

public class JsonBuilder
{
    private StringBuilder json;

    public JsonBuilder()
    {
        json = new StringB         


        
相关标签:
1条回答
  • 2020-12-14 13:49

    You shouldn't manually serialize the return value; ASP.NET will do it for you. Try something like this:

    [WebMethod]
    public static Person GetPersonInfo(string pFirstName, string pLastName)
    {
      // Assuming you have a server-side Person class.
      Person p = new Person();
    
      p.FirstName = "Pseudo" + pFirstName;
      p.LastName = "Tally-" + pLastName;
      p.Address = "5035 Macleay Rd SE";
      p.City = "Salem";
      p.State = "Oregon";
      p.ZipCode = "97317";
    
      // ASP.NET will automatically JSON serialize this, if you call it with
      //  the correct client-side form (which you appear to be doing).
      return p;
    }
    

    If you need to return something more dynamic, like your example seems to be doing, you can use an anonymous type:

    [WebMethod]
    public static object GetPersonInfo(string pFirstName, string pLastName)
    {
      // ASP.NET will automatically JSON serialize this as well.
      return new {
        FirstName = "Pseudo" + pFirstName,
        LastName = "Tally-" + pLastName,
        Address = "5035 Macleay Rd SE",
        City = "Salem",
        State = "Oregon",
        ZipCode = "97317"
      }
    }
    
    0 讨论(0)
提交回复
热议问题