Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...