ASP.NET Web Forms JSON 返回结果

20

我使用asp.net和Web Forms。 在我的项目中,我有asmx Web服务。

[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#中通过静态关键字设置)。 - leojh
2个回答

37

返回列表,并使用[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
        }
    }
})

1
你在 Web Forms 应用程序中,首先如何调用这个 GetSomething URL? - WEFX

-1
public ActionResult MyAjaxRequest(string args)
{
  string error_message = string.Empty;
  try
  {
    // successful
    return Json(args);
  }
  catch (Exception e)
  {
    error_message = e.Message;
  }
} 

这里可能有一个错误


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接