DS kumar
DS kumar

Reputation: 347

How to Send Json String to Controller in mvc4 and Deserialize json

I have the json object like below

Extension = {
"BookMarks":
[{"Name":"User1","Number":"101"},
{"Name":"User2","Number":"102"},
{"Name":"User3","Number":"103"}]}

I want to send this json string to my controller Action method and Deserialize the data

I want to pass the data to the partialview

 public ActionResult ExtensionsDialog(var data)
        {
            return PartialView(data); 
        }

Any help Thanks in advance..

Upvotes: 6

Views: 28697

Answers (5)

Matthew Lowe
Matthew Lowe

Reputation: 1410

I don't think you have to read the input stream yourself. If you provide a model the binder should do it for you.

In your code behind:

    public class StatusInfo
    {
        public int ItemId { get; set; }
        public int StatusId { get; set; }
    }

    [HttpPost]
    public ActionResult EditStatus(StatusInfo info)
    {
        DoSomethingInteresting(info.ItemId, info.StatusId);
        return new EmptyResult();           
    }

And just use the jQuery ajax function like so:

function changeStatus(itemId, statusId) {
    var postData = { "ItemId": itemId, "StatusId": statusId };
    $.ajax({
        url: "/Item/EditStatus",
        type: "POST",
        data: JSON.stringify(postData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status) {
            console.log("success updating status.");
        },
        error: function () {
            console.log("error updating status.");
        }
    });
}

Upvotes: 4

ravisolanki07
ravisolanki07

Reputation: 647

Your script should be like:

Extension = {"BookMarks":[{"Name":"User1","Number":"101"},{"Name":"User2","Number":"102"},{"Name":"User3","Number":"103"}]}
    $.ajax({
    url         :    "@Url.Action("ExtensionsDialog", "Controller")",
    contentType :    "application/json; charset=utf-8",
    dataType    :    "json",
    type        :    "POST",
    data        :      {"data" : Extension }
 });

Action method is same.

 public ActionResult ExtensionsDialog(var data)
    {
        return PartialView(data); 
    }

Upvotes: 0

AthibaN
AthibaN

Reputation: 2087

In your View:

function SendData(){
        var dataToSend = JSON.stringify(data);

        $.ajax({
            type: "POST",
            url: '@Url.Action("YourAction", "YourController")',
            dataType: "json",
            data: dataToSend,
            contentType: "application/json; charset=utf-8",

        });
}

$("#Updatebtn").click(function () {

             sendData(); 
});

In you Model:

public class YourModel
{
  public String Name { get; set; }
  public int Number { get; set; }
}

In your Controller:

[HttpPost]
public ActionResult YourAction()
        {
            var resolveRequest = HttpContext.Request;
            List<YourModel> model = new List<YourModel>();
            resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
            if (jsonString != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                model = (List<YourModel>)serializer.Deserialize(jsonString, typeof(List<YourModel>);
            }
          //Your operations..
         }

Hope this helps.

Upvotes: 11

AlexB
AlexB

Reputation: 7416

You can pass your data via an ajax call like this :

$.ajax({
  url         :    "@Url.Action("YourMethod", "YourController")",
  contentType :    "application/json; charset=utf-8",
  dataType    :    "json",
  type        :    "POST",
  data        :    JSON.stringify({Extension: data})
}).done(function (result) {
  //Check if it's OK
}).fail(function (result) {
  //Check if it is not OK
}).always(function() {
  //Some code executed whatever success or fail
})

.done, .fail and .always are not compulsory, it's just better in my opinion.

Then use it in your Controller as you've done. It should be OK.

Upvotes: 0

ckv
ckv

Reputation: 10838

You can call the action and pass values like this. Just substitute your data with the data I have in the data section.

$.ajax({
                url: '/Schedule/Schedule/Create',
                type: 'POST',
                cache: false,
                datatype: JSON,
                data: {

                scheduleName: ScheduleName,
                description: Desc,
                Hol_Type: JSON.stringify(holidaytype),
                Start_Date: start_date,
                End_Date: end_date,
                Start_Time: StartTime,
                End_Time: EndTime,
                days: JSON.stringify(days),
                rec_type:1

            },
            success: function (data, status) {}});

Upvotes: 0

Related Questions