locked
Send JSON data from ajax script to POST method in Web Api RRS feed

  • Question

  • User-2133486755 posted

    I use the following script.

    <script type="text/javascript">
    $("#Save").click(function () {
    
    var jsonData = ko.toJSON(tuDispInfo);
    
    var url = corewebApiUrl + '/tudisp/Create';
    url = url.replace(/([^:]\/)\/+/g, "$1");
    
    $.ajax({
    dataType: "json",
    url: url,
    type: "POST",
    data: { viewModel: JSON.stringify(jsonData) },
    success: function (data) {
    console.log('Git');
    },
    error: function (xhr, textStatus, errorThrown) {
    console.log(textStatus);
    }
    });
    });
    </script>

    This script calls the following method.

    [Route("~/api/tudisp/Create")]
    [HttpPost]
    public IHttpActionResult Create([FromBody]ViewModel.Dictionary.ViewModel viewModel)
    {
    return Ok();
    }

    I have checked in debugger and parameter named viewModel is null. What can be the reason?

    Friday, November 10, 2017 2:25 PM

Answers

  • User1168443798 posted

    Hi Maciejowy,

    For your issue, you need to specify the content type as “application/json”, and there is no need to add viewModel before jsonData, I suggest you make a test with below code.

        $(document).ready(function () {
            $("#Save").click(function () {
                var viewModel = {
                    id: 1,
                    name: "Boy"
                };
    
                var jsonData = ko.toJSON(viewModel);
                console.log(jsonData);
                //var url = corewebApiUrl + '/tudisp/Create';
                //url = url.replace(/([^:]\/)\/+/g, "$1");
                url = 'http://localhost:55338/api/tudisp/Create';
                $.ajax({
                    contentType:'application/json',
                    url: url,
                    type: "POST",
                    data: jsonData,
                    success: function (data) {
                        console.log('Git');
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log(textStatus);
                    }
                });
            });
    
        });
    

    Best Regards,

    Edward

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 13, 2017 5:43 AM

All replies

  • User1120430333 posted

    I have checked in debugger and parameter named viewModel is null. What can be the reason?

    Of course, the Json data must match the properties of the viewmodel class, because otherwise, no data binding will be done on the parm when the method is called that will result in a null value.

    Friday, November 10, 2017 2:45 PM
  • User-2133486755 posted

    I have changed parameter for System.Net.Http.Formatting.FormDataCollection formData

    The result.

    {\"CultureTexts\":[{\"Culture\":\"en-GB\",\"TuDispTextId\":null,\"ApplicationTextId\":null,\"TuDispDictionaryTextValue\":\"fgdd\",\"ApplicationTextValue\":\"fsdfsdf\"},{\"Culture\":\"en-US\",\"TuDispTextId\":null,\"ApplicationTextId\":null,\"TuDispDictiona...

    The names of properties match do viewmodel, however it still cannot parse JSON to object,

    Friday, November 10, 2017 2:52 PM
  • User475983607 posted

    Null arguments are almost always due to a mismatch between the client object and the method parameters.

    Is there anyway, you can post the view model and JSON produced by the ko.toJSON(tuDispInfo) function?

    var jsonData = ko.toJSON(tuDispInfo);
    console.log(jsonData);

    Friday, November 10, 2017 3:07 PM
  • User-2133486755 posted

    i have checked this.

    console.log(jsonData);

    It displays me proper JSON.

    Friday, November 10, 2017 3:14 PM
  • User475983607 posted

    i have checked this.

    console.log(jsonData);

    It displays me proper JSON.

    There are too many unknowns in the the posted code.  The AJAX function is missing the contentType and dataType properties.  JQuery AJAX default the content type to 'application/x-www-form-urlencoded; charset=UTF-8' which, in my experience, causes an error when submitting JSON formatted data.

    This syntax looks incorrect...

    data: { viewModel: JSON.stringify(jsonData) },

    and probably should be?

    data: jsonData,

    As I understand, ko.toJSON return a string so there is no need for JSON.stringify.

    var jsonData = ko.toJSON(tuDispInfo);

    Lastly, there is no indication that the POSTed JSON properties matches the API method type argument.

    If you want help from the community, consider posting the source code.  Otherwise we can only guess.

    Friday, November 10, 2017 4:47 PM
  • User1168443798 posted

    Hi Maciejowy,

    For your issue, you need to specify the content type as “application/json”, and there is no need to add viewModel before jsonData, I suggest you make a test with below code.

        $(document).ready(function () {
            $("#Save").click(function () {
                var viewModel = {
                    id: 1,
                    name: "Boy"
                };
    
                var jsonData = ko.toJSON(viewModel);
                console.log(jsonData);
                //var url = corewebApiUrl + '/tudisp/Create';
                //url = url.replace(/([^:]\/)\/+/g, "$1");
                url = 'http://localhost:55338/api/tudisp/Create';
                $.ajax({
                    contentType:'application/json',
                    url: url,
                    type: "POST",
                    data: jsonData,
                    success: function (data) {
                        console.log('Git');
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log(textStatus);
                    }
                });
            });
    
        });
    

    Best Regards,

    Edward

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 13, 2017 5:43 AM