0

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?

2
  • 1
    is this JavaScript inside a Razor view? It needs to be, otherwise the @Url.Action won't work. Commented Nov 21, 2018 at 14:33
  • 1
    No, it's not about Razor View. Because i point a breakpoint for GetJsonData method, and the method works... Commented Nov 21, 2018 at 14:38

1 Answer 1

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);
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

I created an object with a property user but it still returns null...
@sudu That's because of return null; in the method GetJsonData.
No, i mean GetJsonData parameter's user returns null
@sudu Oh, sorry. I've updated the second way, you can try again. I've removed dataType property, and added 2 properties contentType and processData.
Thanks a lot @Tân Nguyễn, updated way solved my proplem :)
|

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.