0

I have a question about reading a JSON string in C#. My scenario is following.

I have ASP.NET MVC C# project(.NET framework 3.5). In LobbyController I have

. 
.
.
using System.IO;
using System.Web.Script.Serialization;
.
.
.
[HttpPost]
public ActionResult SomeMethod(string sampleData)
{
    //do stuff here
}

and in jquery script file I have defined click function

$("#buttonID").click(function() {
    var sampleData = {
            "property1": $('#elementID1').val(),
            "property2": $('#elementID2').val(),
            "property3": $('#elementID3').val()
        };

    $.ajax({
        url: "/Lobby.aspx/SomeMethod",
        type: "POST",
        data: sampleData,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function() { $('#message').html('Success').fadeIn(); },
        error: function() { $('#message').html('Error').fadeIn(); }
    });
});

Now, on click ajax function kicks in and SomeMethod is called in controller as expected but sampleData parameter is null. I also tried modifiing "data" line in ajax function like this: data: JSON.stringify(sampleData), but it didn't work as well.

I tried to alert individual properties of sampleData object and they had value they're supposed to have but for some reason ActionMethod's sampleData parameter is null. Could someone tell me what I'm missing? Maybe it's a syntax error on my part or there is something that needs to be done on c# side?

Any help would be appreciated

2
  • Show us the generated json string. This is most probably the key thing here. Commented Mar 29, 2012 at 12:44
  • Generated string is {"RaceName":"Human","StatOrigValue":"14","FreePts":"5"} Commented Mar 29, 2012 at 12:51

5 Answers 5

2

You can use a model class to bind your client data, the MVC3 has built-in support for JSON binding.

There is a example in this blog post.

Sign up to request clarification or add additional context in comments.

Comments

0

You're passing a JSON object into the action, not a string. You are close with the JSON.stringify:

data: "sampleData=" + encodeURIComponent(JSON.stringify(sampleData))

That should send a string to the server containing the JSON representation of the sampleData object

1 Comment

This generates this string: stat=%7B%22RaceName%22%3A%22%C4%8Clov%C4%9Bk%22%2C%22StatOrigValue%22%3A%2214%22%2C%22FreePts%22%3A%225%22%7D but parameter of ActionResult is still null
0

Just create a class that covers the JSON model, I assume you have MVC3 which has JSON model binding built-in.

public class MyModel
{
    public string RaceName{get; set;}
    public int StatOrigValue{get; set;}
    public int FreePts{get; set;}
}

[HttpPost]
public JsonResult SomeMethod(MyModel sampledata)
{
    //do stuff here
   return new JsonResult {Data =  new {Success = "Success"}}
}

1 Comment

Thank you. That's how I originally had it(except JsonResult return type) with model class defined but that didn't work so I tried to use string. I had to combine it with part of Tommy's solution.
0

Since you are using .NET 3.5, I am assuming you are using MVC2. I just encountered the same issue last week. I had to do a few things:

  1. Download and reference the JQuery JSON plugin in your view/master layout page/whereever.

  2. Download the ASP.NET MVC 2 Futures Library and reference the Microsoft.Web.Mvc.dll assembly.

  3. Change data: sampleData to data: $.toJSON(sampleData)

  4. In your global.asax, add using System.Web.Mvc;. Then in your Application_Start() method, add the line ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

This made it possible to send JSON to my controller action method. I was getting the same crazy URLencoded mess that you were before I stumbled across this method. My basis for this information comes from a Phil Haacked article here.

2 Comments

Thank you for your help. This solved the problem. I combined this with whosrdaddy's solution and changed method signiture to use custom model class and return JsonResult. I'd mark helpful answers but I don't have necessary reputation yet.
@LetThereBeByte: Awesome man, glad it worked for you, getting a working solution is more important than a few SO points :)
0

Thank you all for your help.

Since I used combination of more answers I will sum it up here. What I had to do was to redefine sampledata object in jquery where property names were not enclosed in quotation marks. Then I followed Tommy's answer. Finally I changed my SomeMethod signature to return JsonResult type and accept custom defined model class as parameter as per whosrdaddy's answer. I'd mark your posts as useful but I don't have enough reputation yet. Once again thank you all for your posts.

Just a quick note. In point no. 4 of Tommy's answer you need to reference Microsoft.Web.Mvc.dll assembly you've downloaded but I'm sure you'd all figure it out.

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.