0

I have the following JQuery code;

var selectedval = $("#PaymentApplication_System").val();
var text = $("#btnSave").val();
var payVal = $("#PaymentApplication_Amount").val();
var dbobj = [{ param: text, value: payVal}];
var jlist = $.toJSON(dbobj);

which gives me the following json object;

[{"param":"Update Payment","value":"50.00"}]

I am using MVC 2. how do I read the values from the object in my controller???

alexn
  • 57,867
  • 14
  • 111
  • 145
JamaicasFinest
  • 73
  • 4
  • 13

3 Answers3

2

MVC 2 does not automatically convert your JSON string to a C# object. You can use the JavaScriptSerializer which is located in System.Web.Script.Serialization. Example:

public ActionResult Index(string customerJson)
{
    var serializer = new JavaScriptSerializer();
    var customer = serializer.Deserialize<Customer>(customerJson);

    return View(customer);
}

This would do pretty good as an extension metod (or put it in a base controller if you have any):

public static class ControllerExtensions
{
    public T JsonDeserialize<T>(this Controller instance, string json)
    {
        var serializer = new JavaScriptSerializer();
        return serializer.Deserialize<T>(json);
    }
}

You can then use it as:

public ActionResult Index(string customerJson)
{
    var customer = this.JsonDeserialize<Customer>(customerJson);

    return View(customer);
}
alexn
  • 57,867
  • 14
  • 111
  • 145
1

I think this post can help which is having similar problem:

Deserialize JSON Objects in Asp.Net MVC Controller

Community
  • 1
  • 1
Prashant Lakhlani
  • 5,758
  • 5
  • 25
  • 39
0

MVC 2 does not convert JSON objects to Models while MVC 3 does.

You have to use JSON.net.

Aliostad
  • 80,612
  • 21
  • 160
  • 208