【问题标题】:asp.net web forms json return resultasp.net web表单json返回结果
【发布时间】:2011-07-18 20:55:57
【问题描述】:

我使用 asp.net 和 web 表单。 在我的项目中,我有 asmx 网络服务

[WebMethod]
    public string GetSomething()
    {
      // avoid circual reference(parent child)
      List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
      string res1 = res.ToJson();
      // extension methods
      return res.ToJson();
    }

结果就是这种格式。

[
    {"User_ID":1,"User_Name":"Test 1","Date_Expire":null},
    {"User_ID":2,"User_Name":"Test 2","Date_Expire":null}
]

我怎样才能在 $.ajax 中附加标签这个结果来获得这个输出:

1 - 测试 1、2 - 测试 2。

【问题讨论】:

  • web方法也应该是类成员(在C#中由static关键字设置)

标签: asp.net json jquery


【解决方案1】:

改为返回列表,并使用 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 属性 - 它会自动创建 JSON 对象作为返回:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public List<RetUsers> GetSomething()
{
  // avoid circual reference(parent child)
  List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();

  return res;
}

在 JS 方面:

$.ajax(
{
    type: "POST",
async: true,
url: YourMethodUrl,
data: {some data},
contentType: "application/json; charset=utf-8",
dataType: "json",
    success: function(msg)
    {
        var resultAsJson = msg.d // your return result is JS array
        // Now you can loop over the array to get each object
        for(var i in resultAsJson)
        {
            var user = resultAsJson[i]
            var user_name = user.User_Name
            // Here you append that value to your label
        }
    }
})

【讨论】:

  • 在 web-forms 应用程序中,如何首先调用这个 GetSomething URL?
猜你喜欢
  • 2016-12-04
  • 2013-05-26
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多