views:

172

answers:

1

How to return values from Webmethod to the client in JSON format?

There are two static int values that i want to return.
Do I need to create new object with those 2 properties and return it?
The GetStatus() method is called frequently and i don't like the idea of creating a special object each time just for json formatting...

[WebMethod]
public static int GetStatus()
{
        int statusProcess,statusProcessTotal;

        Status.Lock.EnterReadLock();
        statusProcess=Status.Process; //Static field
        statusProcessTotal=Status.ProcessTotal; //Static field        
        Status.Lock.ExitReadLock();


        return ...
}

On client side I catch the return value in :
function OnSucceeded(result, userContext, methodName)
(PageMethods.GetStatus(OnSucceeded, OnFailed);)

A: 

I would just go with an object. It fits with what you need to do. If you have two return values you have to put them together in a structured way.

  public class StatusResult
        {
            public int StatusProcess { get; set; }
            public int StatusProcessTotal { get; set; }
        }

  [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public StatusResult GetStatus()
        {
            int statusProcess,statusProcessTotal;

            //Status.Lock.EnterReadLock();
            statusProcess = 5;
            statusProcessTotal = 1; //Static field        


            var result = new StatusResult();
            result.StatusProcess = statusProcess;
            result.StatusProcessTotal = statusProcessTotal;

            return result;
        }
Jason Rowe
Can you give an example?
kenny
Ok, added a working example now.
Jason Rowe
What about recreating new object every time the method is called? Doesn't it affect efficiency?
kenny
I've never had a problem. I think you are over thinking it.
Jason Rowe
lol, i got 2 answers and both of them -1
kenny
It happens to the best of us.
Jason Rowe
I've voted you up :) . If there won't be any new answer i will accept yours.
kenny