开发者

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


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


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

Deserialize JSON Objects in Asp.Net MVC Controller


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

You have to use JSON.net.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜