Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
DS kumar Avatar asked Oct 10 '13 09:10

DS kumar


1 Answers

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.

like image 166
AthibaN Avatar answered Sep 20 '22 13:09

AthibaN