suleymanduzgun
suleymanduzgun

Reputation: 425

How To Post Json Data To Controller Without a Model in .net core

There is a huge data stored in grid that comes from a sql query joined more than ona table. Data type is Json. I filtered data and then want to sent filtered data to controller. But how it can be? Here is test json data in javascript block:

var jsonData = {
    "FirstName": "John",
    "LastName": "Doe",
    "DoB": "01/01/1970" };

And this is my javascript function:

function submitForm() {
    var user = jsonData;

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("GetJsonData", "Account")",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(user),
        success: function (data) { alert(data); },
        failure: function (errMsg) {
            alert(errMsg);
        }
    });
}

How to get the Json data in controller? Here is my [HttpPost] method:

    [HttpPost]
    public IActionResult GetJsonData(String user)
    {
        //...
        return null;
    }

user gets null.. Should i change type "String" in method or something else?

Upvotes: 0

Views: 1033

Answers (1)

Tân
Tân

Reputation: 1

Since user is a string, you could try to create an object with a property user:

jQuery.ajax({
    type: "POST",
    url: "@Url.Action("GetJsonData", "Account")",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: { 
        user: JSON.stringify(user) 
    },
    success: function (data) { alert(data); },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Or using FormData:

var formData = new FormData();
formData.append('user', JSON.stringify(user));

jQuery.ajax({
    type: "POST",
    url: "@Url.Action("GetJsonData", "Account")",
    contentType: false,
    processData: false,
    data: formData,
    success: function (data) { alert(data); },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Upvotes: 1

Related Questions