从c#中检索多个值到JavaScript

本文关键字:JavaScript 检索 | 更新日期: 2023-09-27 18:08:26

我有一个带有onclick:

a标签
<a onclick="join(4);">Join</a>

现在,当点击a标签时,它按以下顺序调用代码:

JavaScript函数:

function join(gymID) {
        PageMethods.getGymInformation(gymID);
    }
c#方法:

[WebMethod]
public gymData getGymInformation(string gymID)
{
    gyms gym = new gyms();
    DataTable dt = gym.getNewGymInfo(System.Convert.ToInt32(gymID));
    DataRow dr = dt.Rows[0];
    return new gymData { name = dr["name"].ToString(), strength = dr["strength"].ToString(), speed = dr["speed"].ToString(), defence = dr["defence"].ToString()};
}
public DataTable getNewGymInfo(int gymID)
{
    // This returns a datatable with 1 row
    return gymTableApapter.getNewGymInfo(gymID);
}
[Serializable]
public sealed class gymData
{
    public string name { get; set; }
    public string strength { get; set; }
    public string speed { get; set; }
    public string defence { get; set; }
}

正如您所看到的,JavaScript join函数调用c#方法,然后检索包含1行的DataTable,然后使用自定义数据类型填充要返回的数据的字符串。

现在我想弄清楚如何从c#方法返回的信息在JavaScript连接函数中提取?

他们是这样做的吗?

从c#中检索多个值到JavaScript

在JavaScript代码中添加成功/错误回调。它可能看起来像这样:

PageMethods.getGymInformation(gymID, onSuccess, onError);
function onSuccess (result) {
    // result contains the returned value of the method
}
function onError (result) {
    // result contains information about the error
}

那么在onSuccess函数中,您将在result变量中获得服务器端方法(类型为gymData)的返回值。此时,您可以在客户端代码中对它做任何需要做的事情。

如果这些函数没有任何可重用的地方,你甚至可以直接在行内添加它们:

PageMethods.getGymInformation(gymID,
    function (result) {
        // success
    }, function (result) {
        // error
    });