0

I have created an ASP.NET C# project which consists of a web form and a WebSocket handler. I would like to send 2 data (name & price data) from the web form in JSON string format to the WebSocket handler. Here is the code snippet in the web form:

            ws.onopen = function()
           {

               var name = "Client Product";
               var price = 10.8;
               ws.send(JSON.stringify(name));
               ws.send(JSON.stringify(price));
              alert("Message is sent...");
           };

In the WebSocket handler's OnMessage(string) method, I would like to retrieve the 2 data sent by the web form and deserialize the 2 data to c# format. Here is the code snippet in the WebSocket handler:

     public override void OnMessage(string message)
    {
        string serverName="";
        string serverPrice = "";

        serverName = JsonConvert.DeserializeObject<string>(message);
        serverPrice = JsonConvert.DeserializeObject<string>(message);

    }

However, under the WebSocket handler's onMessage(string) method, both the variable serverName and serverPrice would be assigned as "Client Product". I want the variable serverPrice to be assigned as "10.8", instead of "Client Product".

Can somebody please tell me how I could achieve that? WILL really appreciate if you could help me :) Thank You :)

1 Answer 1

2

If you want to send multiple pieces of data in a single JSON message, you'll need to combine them into an object. Try it like this:

On the client:

ws.onopen = function()
{
    var obj = {
        name: "Client Product",
        price: "10.8"
    };
    ws.send(JSON.stringify(obj));
    alert("Message is sent...");
};

On the server:

public override void OnMessage(string message)
{
    MyData obj = JsonConvert.DeserializeObject<MyData>(message);

    string serverName = obj.Name;
    string serverPrice = obj.Price;

    ...
}

public class MyData
{
    // Important: these JsonProperty attributes MUST match
    // the names of the properties in the client object

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("price")]
    public string Price { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.