Search code examples
c#.netasp.net-coredatatableasp.net-core-2.2

How to map DataTable parameters in controller (MVC Core 2.2)?


I'm trying to send the datatable parameters to the server, however what used to work in .NET Framework doesn't seem to work in .NET Core. It seems it only fails to map the objects within the main DTParameters object, as I get the values of Length, Draw, Start.

The DTParameters class:

public class DTResult<T>
{
    public int draw { get; set; }

    public int recordsTotal { get; set; }

    public int recordsFiltered { get; set; }

    public IEnumerable<T> data { get; set; }
}

public abstract class DTRow
{
    public virtual string DT_RowId
    {
        get { return null; }
    }

    public virtual string DT_RowClass
    {
        get { return null; }
    }

    public virtual object DT_RowData
    {
        get { return null; }
    }
}

public class DTParameters
{
    public int Draw { get; set; }    

    public DTColumn[] Columns { get; set; }

    public DTOrder[] Order { get; set; }

    public int Start { get; set; }

    public int Length { get; set; }

    public DTSearch Search { get; set; }

    public string SortOrder
    {
        get
        {
            return Columns != null && Order != null && Order.Length > 0
                ? (Columns[Order[0].Column].Data + (Order[0].Dir == DTOrderDir.DESC ? " " + Order[0].Dir : string.Empty))
                : null;
        }
    }

    public int SearchOption { get; set; }

}

public class DTColumn
{
    public string Data { get; set; }

    public string Name { get; set; }

    public bool Searchable { get; set; }

    public bool Orderable { get; set; }

    public DTSearch Search { get; set; }
}

public class DTOrder
{
    public int Column { get; set; }

    public DTOrderDir Dir { get; set; }
}

public enum DTOrderDir
{
    ASC,
    DESC
}

public class DTSearch
{
    public string Value { get; set; }

    public bool Regex { get; set; }
}

The ajax call:

ajax: {
    "type": "GET",
    "url": '@Url.Action("GetCompanies", "Company")',                     
    "data": function (data) {
        return data;
     }

I've always used function (data) { return data = JSON.stringify(data); }, but I had to remove stringify here in order to get at least some values sent to the server.

In Startup.cs:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
            {
   options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
}); 

And finally, the CompanyController:

public object GetCompanies(DTParameters param)
{    
    return _companyService.GetCompaniesForDatatable(param, CurrentClient);
}

The Search property of param is always null.


Solution

  • So I changed the method from GET to POST and it worked. Now I'm getting all the values I need.

    Huh...