Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Alex Brown 129 posts 620 karma points
    Sep 22, 2017 @ 07:38
    Alex Brown
    1

    Posting JSON to an API Controller

    Hi

    I've seen numerous topics about people struggling to post an object to a controller, but none of them have really helped.

    I've got a JSON object which has two arrays, one isn't populated so I expect it to be null (which it is):

    "{"locationTypes":["Location Type"],"countries":[]}"
    

    I'm using $.post to send this to the controller.

    var getResults = function (selectedFilters, onSucess, onError) {
        $.post("/Umbraco/Api/Contact/GetResults", JSON.stringify(selectedFilters)).then(onSucess, onError);
    }
    

    Controller method:

        [System.Web.Http.HttpPost]
        public ContactPageViewModel GetResults(ContactSelection selectedFilters)
        {
            return new ContactPageViewModel();
        }
    

    ContactSelection object:

    public class ContactSelection
    {
        public List<string> LocationTypes { get; set; }
        public List<string> Countries { get; set; }
    }
    

    The controller is hit by the post, however selectedFilters' properties are both null.

    Any help would be appreciated, thanks.

  • Alex Brown 129 posts 620 karma points
    Sep 22, 2017 @ 07:46
    Alex Brown
    1

    Alright just got it working. For some odd reason I need to use this implementation of post:

        $.ajax({
            type: "POST",
            url: "/umbraco/api/Contact/GetResults/",
            contentType: "application/json; charsect=utf-8",
            dataType: "json",
            data: JSON.stringify(selectedFilters)
        }).then(onSucess, onError)
    

    I'd really like to know why though. If someone could answer that then I'll hand them a cookie.

  • Duncan Bannister 5 posts 76 karma points notactivated
    Oct 06, 2017 @ 11:38
    Duncan Bannister
    0

    You are able to use the $.post method.

    If you specify your parameter name as "selectedFilters" in the Controller. You will have to set the variable name in the $.post function.

    $.post("/Umbraco/Api/Contact/GetResults", { 
       selectedFilters : JSON.stringify(selectedFilters) 
    }, function(data) {
        console.log(data);
    });
    

    Hope this works.

Please Sign in or register to post replies

Write your reply to:

Draft