[ASP.net] Json 문자열을 컨트롤로로 보내고 deserialize 하는 방법

Posted by RAY.D
2015. 4. 27. 10:17 Web/ASP.NET MVC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.




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.



A:

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.










http://stackoverflow.com/questions/19291530/how-to-send-json-string-to-controller-in-mvc4-and-deserialize-json