Search code examples
javascriptc#webmethod

Retrieving multiple values from C# to JavaScript


So I have an a tag with an onclick:

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

Now when the a tag is clicked, it calls this code in this order:

JavaScript function:

function join(gymID) {
        PageMethods.getGymInformation(gymID);
    }

C# method:

[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; }
}

As you can see, the JavaScript join function calls the C# method which then retrieves a DataTable with 1 row, then using a custom data type it populates the strings with data to be returned..

Now I'm trying to figure out how to get the information returned from the C# method to be extracted in the JavaScript join function?

Is their a way to do this?


Solution

  • Add success/error callbacks in your JavaScript code. It might look something like this:

    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
    }
    

    Then in the onSuccess function you would have the returned value of the server-side method (of type gymData) in the result variable. At that point you can do whatever you need to do with it in your client-side code.

    If the functions don't have any applicable re-use, you can even just add them in-line:

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