'.net5 with Ajax call

I tried to call action in the controller using Ajax call. The call is work fine, but in the same action I have data table and I got error on the code var draw = HttpContext.Request.Form["draw"].FirstOrDefault(); and the error is incorrect content-type application/json charset=utf-8.

this is my ajax call

    $(function () {
    $.ajax({
      
       url: "@Url.Action("get_600UpdateFailuer", "_600PermitFailuer")",
       // url: '/_600PermitFailuer/get_600UpdateFailuer', 
         type: "GET",
        data: '{}',
        contentType: "application/json",
        dataType: "json",
        traditional: true,
         success: function(res) {
    window.location.href = url;
           },
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    });

});

and this is my controller

public JsonResult get_600UpdateFailuer()
    {
        //var TransactionLogId = Request.Cookies["TransactionLogId"];
        var InstructorId = Request.Cookies["InstructorId"];
        try
        {

            var draw = HttpContext.Request.Form["draw"].FirstOrDefault();   
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() +
                                          "][name]"].FirstOrDefault();
            var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;


            var classData = (from T in _db1.TransactionLogs
                                 //where C.MonitorId == InstructorId
                             select new TransactionLog
                             {
                                 TransDesc = T.TransDesc,
                                 TransType = T.TransType,
                                 TransDateTime = T.TransDateTime
                             }).ToArray().AsQueryable();  // This will return IQueryable<T>

            if (!(string.IsNullOrEmpty(sortColumn)))
            {
                classData = classData.OrderBy(sortColumn + " " + sortColumnDirection);
            }
            if (!string.IsNullOrEmpty(searchValue))
            {
                classData = classData.Where(m => m.TransDesc != null && m.TransDesc.ToLower().Contains(searchValue)
                                            || m.TransType != null && m.TransType.Contains(searchValue));
            }

            recordsTotal = classData.Count();
            var data = classData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new
            {
                //draw = draw,
                recordsFiltered = recordsTotal,
                recordsTotal = recordsTotal,
                data = data
            };
            return Json(jsonData);
        }
        catch (Exception ex)
        {
            throw ex.InnerException;
        }
    }


Solution 1:[1]

According to the documentation for Request.Form:

The Form property is populated when the HTTP request Content-Type value is either "application/x-www-form-urlencoded" or "multipart/form-data".

But the content type you're using is:

contentType: "application/json"

So you could update your contentType to use something that is compatible with Request.Form, and probably use a POST request instead of GET. Or, even better, don't use Request.Form at all and instead let the framework's model binding work for you and have the controller action method accept a parameter of the type you're looking for. (Which you may need to explicitly create.)

For example, if you were to send an object like this to the server:

data: {
  someProperty: 123,
  anotherProperty: 'this is a test'
}

Then in your server-side code you might define a class like this:

public class MyRequestDTO
{
    public int SomeProperty { get; set; }
    public string AnotherProperty { get; set; }
}

Which your method would accept as a parameter:

public JsonResult get_600UpdateFailuer(MyRequestDTO input)

Then within that method you should have the populated object. Whatever the more complex shape of the object you need happens to be, you may need to reverse-engineer the tool you're using and observe the shape of the data it sends to the server. Your browser's debugging tools will be very helpful in that regard.


However...

Despite your assertions to the contrary, in order to complete the implementation of your functionality you are still going to have to send data to the server. Currently your AJAX request sends an empty object:

data: '{}'

An empty object will contain none of the values you're looking for in the server-side code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1