AppNove
AppNove

Reputation: 73

Read JSON object in Controller

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???

Upvotes: 0

Views: 7776

Answers (3)

Prashant Lakhlani
Prashant Lakhlani

Reputation: 5806

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

Deserialize JSON Objects in Asp.Net MVC Controller

Upvotes: 1

alexn
alexn

Reputation: 58952

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

Upvotes: 2

Aliostad
Aliostad

Reputation: 81660

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

You have to use JSON.net.

Upvotes: 0

Related Questions