简体   繁体   中英

Getting 500 internal server error when passing Json to MVC controller

I want to pass 2 list string json to my controller and compare the changes.

Here is my model

public class PhongtreeView
{
    public Guid Id { get; set; }
    public Guid? ParentId { get; set; }
}

And my controller

public ActionResult SaveChanges(IEnumerable<PhongtreeView> InitTree,IEnumerable<PhongtreeView> UpdatedTree)
    {
        //Compare changes
        return View();
    }

My Ajax code

$("#SaveChanges").click(function () {
    getJson();

    $.ajax({
        url: '@Url.Action("SaveChanges", "Phong")',
        type: "POST",
        data: {
            JSonFirst: JSON.stringify(StartTreeJson),
            JSonFinal: JSON.stringify(UpdatedTreeJson)
        },
        datatype: "json",
        contentType: "application/json",
        success: function (data) {
            if (!data.error) {
                alertify.success(" Success");
                //window.location.reload();

            }
            else {
                alertify.error(data.message);
            }
        }
    });   

But i always get the 500 internal error.If i remove the contentType: "application/json" it can run but it only pass null value to controller. Can someone tell me what's wrong ? Thank in advance.

You cannot pass 2 complex types to action method directly. The way to be done is shown below:

Create a class

public class Tree
{
    public List<PhongtreeView> InitTree { get; set;}
    public List<PhongtreeView> UpdatedTree { get; set;}
}

Your action method:

public ActionResult SaveChanges(IEnumerable<Tree> trees)
{
    //Compare changes
    return View();
}

In Js side, you need to set the data as follows:

var StartTreeJsonData = [{Id : 1, ParentId : 1},{Id : 2, ParentId : 2}];
var UpdatedTreeJsonData = [{Id : 10, ParentId : 10},{Id : 20, ParentId : 20}];

data: '{InitTree : StartTreeJsonData, UpdatedTree : UpdatedTreeJsonData}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM