Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...