0

I have found many answers for posting 1 array of objects to MVC, but I'm struggling with multiple. It's probably something small I'm missing.

This is my JS:

 $.ajax({
                type: "POST",
                url: encodeURI("<%:Url.Action("SaveSimulator")%>"),
                data: JSON.stringify({ 
                    gevelshapes: (gevelshapes), 
                    gevelgaten:(gevelgaten),
                    dakshapes:(dakshapes),
                    dakgaten:(dakgaten),
                    dakrandshapes:(dakrandshapes), 
                    dakrandgaten:(dakrandgaten) 
                }),
                success: function(data){
                    $("form").submit();
                },
                contentType: 'application/json',
                dataType: "json"
            });

These are arrays containing objects with an x and y coordinate. Like so:

var gevelshapes = [{ x: "1", y: "2" },{ x: "2", y: "1" }];

My MVC controller looks like this:

[HttpPost]
    public JsonResult SaveSimulator(List<Coordinaat> gevelshapes , List<Coordinaat> dakrandshapes, List<Coordinaat> dakshapes,List<Coordinaat> gevelgaten , List<Coordinaat> dakrandgaten, List<Coordinaat> dakgaten)
    {

        //do something 
    }

I am missing something because MVC thinks that List<Coordinaat> gevelshapes has 1 object with an empty x and y string instead of an array with 2 'coordinaat' objects.

Any help would be great :)

1 Answer 1

0

Maybe I'm wrong but mvc does not automatically parse Json string. Try like this:

 $.ajax({
            type: "POST",
            url: encodeURI("<%:Url.Action("SaveSimulator")%>"),
            data: { x : JSON.stringify({ 
                gevelshapes: (gevelshapes), 
                gevelgaten:(gevelgaten),
                dakshapes:(dakshapes),
                dakgaten:(dakgaten),
                dakrandshapes:(dakrandshapes), 
                dakrandgaten:(dakrandgaten) 
            }) },
            success: function(data){
                $("form").submit();
            },
            contentType: 'application/json',
            dataType: "json"
        });

[HttpPost]
public JsonResult SaveSimulator(string x)
{
     var serializer = new JavaScriptSerializer();
     var result = serializer.Deserialize<object>(x); // You can cast to your preffered class
     // ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.