0

Ajax post parameter always NULL in MVC controller

I have a MVC project, which uses .Net Core.

In one of the shared layout, I have the javascript:

var requestData = { term:"myReport" };
var myData = JSON.stringify(requestData);

$.ajax({
    url: '@Url.Action("ReportErrorData", "OperationReport")',
    type: 'POST',
    data: myData,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: function (xhr) {
        alert('Error: ' + xhr.statusText);
    },
    success: function (result) {
        $('#divError2').text(result);
        }
    });
});

In the controller, I have

public ActionResult ReportErrorData(string term)
{
    var error = string.Empty;
    try
    {
        ....
    }
    catch (Exception ex)
    {
        .....

        error = ex.ToString();
    }
    ....
    var r = new JsonResult(error);
    return r;
}

For some reasons, when it reaches the controller, the variable term is always null. However, if I use developer tool, I can see the request body is:

{'term':'myReport'}

I did the same thing in MVC4 project, and it worked fine. Could this because of .Net Core?

Thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91
  • Is it possible that you meant var requestData = { "term": "myReport" }; instead of var requestData = { term:"myReport" }; (note quotes) – Ian Feb 09 '17 at 18:13
  • @urlreader It work for meee.... var requestData = { term: "myReport" }; var myData = JSON.stringify(requestData);$.ajax({ url: '@Url.Action("ReportErrorData", "Home")', type: 'POST', data: myData, contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function () { alert("error"); } }); – Dhiren Patel Feb 09 '17 at 18:34
  • Note that it can be just `data: requestData,` and delete the `contentType` option (there is no need to stringify the data) –  Feb 09 '17 at 20:27

0 Answers0