3

I am making an AJAX POST request to an MVC controller, yet the data is coming through as null. I'm not sure why.

$(document).ready(function() {
  $("#btnSaveCustomer").click(function() {
    debugger; 
    var data = {
      _DcLink: "1",
      _Account: "Test",
      _Name: "TestName",
      _Title: "Mr",   
      _Init: "T"
    }

    $.ajax({
      method: "POST",
      url: '/Customer/SaveCustomer',
      data: JSON.stringify(data),
      success: function() {
        debugger;
        console.log(data)
        alert("Success")
      },
      error: function() {
        alert("Error")
      }
    });
})
public ActionResult SaveCustomer(string data)
{
  using (var ms = new MemoryStream(Encoding.UTF32.GetBytes(data)))
  {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Customer));
    Customer serializeddata = (Customer)deserializer.ReadObject(ms);
  }
  return Json(new { Success = true });
}

No matter how I try to serialize the data it is always null. I believe the AJAX POST method is not executing properly

I am using dummy data in order to resolve the problem.

The code hits a breakpoint at MemoryStream in the controller - stating data is null.

System.ArgumentNullException: 'String reference not set to an instance of a String. Parameter name: s'

Any help appreciated

0

4 Answers 4

3

It's because the ModelBinder is expecting a property in the JSON named data, yet you're not sending that; all the properties are in the root object. That would work fine if you were binding to a model, but as you're not you need to amend the data structure in your JS slightly, to this:

var data = { 
  data: {
    _DcLink: "1",
    _Account: "Test",
    _Name: "TestName",
    _Title: "Mr",   
    _Init: "T"
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey Rory Thank you for the correction. I see why that would be a problem. Ive made the changes and am still getting the exact same error. Must be something else, Any ideas on maybe a better way to do this?
1

change like this;

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

1 Comment

Ahh, That seems to have fixed.. Thank you
0

Having same issues. AJAX call fails. If I remove [FromBody] from controller then the ajax call is successful however, the data is null. I am using .NET Core 3.1 and razor pages

 <script>
      $(document).ready(function () {
        var data = { "name": "John Doe" }
        $.ajax({
            url: "/membership/tester/",
            type: "POST",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            headers: {
                RequestVerificationToken: 
                $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            success: function (data) {
                alert('Survey submitted successfully');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.status);
                  }
               }
          });
       });
    </script>

Here is the controller code

[Route("membership/tester")]
[HttpPost]
public ActionResult Test([FromBody] string somedata)
{
    var data = somedata;
    return Json(data);
}

1 Comment

So apparently the issue is related to the naming convention. The parameter name in the controller method must match what's specified in the ajax call. To make it work I had to make the following change in ajax call. url: "/evaluations/surveysave/", type: "POST", data: { somedata: JSON.stringify(result.data) },
-2
$(document).ready(function() {
  $("#btnSaveCustomer").click(function() {
    debugger;
    var data = {
      _DcLink: "1",
      _Account: "Test",
      _Name: "TestName",
      _Title: "Mr",
      _Init: "T"
    }

    $.ajax({
      method: "POST",
      url: '/Customer/SaveCustomer',
      data: JSON.stringify(data),
      success: function(data) {
        debugger;
        console.log(data)
        alert("Success")
      },
      error: function() {
        alert("Error")
      }
    });
  })

2 Comments

add data in the success function bracket success: function (data) { debugger; console.log(data) alert("Success")
Firstly, what exactly have you changed? Secondly, please take the time to describe what the issues are and why this solution helps.

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.