Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API post data: object reference not set to an instance of an object

I am trying to get Web API working with POST and I have the following in my Controller:

public class mainGridController : ApiController
    {

        public class formData
        {
            public string module { get; set; }
            public string group { get; set; }
            public string staff { get; set; }
        }

        public HttpResponseMessage Post([FromBody] formData data)
        {
            string string_group = "";
            string string_staff = "";

            if (data.group != null)
            {

But I seem to be getting "object reference is not set to an instance of an object" for data.group in my "if" statement.

Here is my route info:

protected void Application_Start(object sender, EventArgs e)
        {
             GlobalConfiguration.Configuration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{data}",
            defaults: new { module = System.Web.Http.RouteParameter.Optional, data = System.Web.Http.RouteParameter.Optional}
            );
        }

Does anyone know what could be causing this? I am trying to post using jQuery.

Here is my jQuery code:

var url = "api/mainGrid";
var source = {
    datatype: 'json',
    contentType: 'application/json; charset=utf-8',
    url: url,
    processData: false,
    type: "POST",
    id: "SEQUENCE",
    root: 'rowsinfo',
    cache: false,
    columns: [],
    datafields: [],
    beforeprocessing: function (data) {
        var columnsdata = new Array();
        var datafieldsdata = new Array();
        for (k in data.columnsinfo) {
            var col = {};
            col.text = data.columnsinfo[k]["DISPLAYNAME"];
            col.datafield = data.columnsinfo[k]["DISPLAYNAME"];
            var datafields = {};
            datafields.name = data.columnsinfo[k]["DISPLAYNAME"];
            columnsdata.push(col);
            datafieldsdata.push(datafields);
            source.columns = columnsdata;
            source.datafields = datafieldsdata;
        }
        $("#jqxgrid").jqxGrid({ columns: source.columns });
    },
    data: {
        group: JSON.stringify(checkedGroups),
        staff: JSON.stringify(checkedStaff),
        module: selectedModuleSEQ
    }
};

Thanks

like image 654
realtek Avatar asked Sep 19 '25 03:09

realtek


1 Answers

The problem is you have specified the dataType parameter as json but you are passing a JS object - which of course isn't JSON.

You need to convert your data object to actual JSON for this to work

data: JSON.stringify({
    group: JSON.stringify(checkedGroups),
    staff: JSON.stringify(checkedStaff),
    module: JSON.stringify(selectedModuleSEQ)
}),
like image 150
James Avatar answered Sep 20 '25 19:09

James