Home > Net >  Datatables.net and asp.net core WebApi get search[value]
Datatables.net and asp.net core WebApi get search[value]

Time:11-03

I'm trying to figure out server-side processing in Datatables.net with an asp.net core WebApi-Controller.

DT is sending an http-get to the controller with some given parameters as described here: SearchValue sent to controller

But as you can see here the value of search is null. Search is null

All other parameters were filled in my controller.

So I think the problem is this search**[value]**-thing. How do I tell the controller to read this parameter?

As you see in my second screenshot I also tried to define were to get the parameter from. But wether [FromHeader] nor [FromQuery] works.

Thanks for your help and suggestions. Patrick

CodePudding user response:

I've figured out how to solve it.

I simply used the HttpContext-Class to get the Query named "search[value]".

Like so:

var searchWord = HttpContext.Request?.Query["search[value]"].ToString();

Don't know if this is the clean way, but it works.

CodePudding user response:

I've used contentType: "application/json" when I made request from the UI

const table = $('#datatableDefault').DataTable({
    ajax: {
        url: '/endpoint_toServer',
        method: 'post',
        contentType: "application/json",
        data: function (d) {
            // Add your additional data if needed 
            d.fromDate = date[0];
            d.toDate = date[1];

            return JSON.stringify(d);
        }
    },
    serverSide: true,....

And in controller

 var queryString = new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
 var requestParams = JsonConvert.DeserializeObject<CustomDataTableRequest>(queryString.Result);

public class CustomDataTableRequest: DatatableRequest
{
    
    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }

}

public class DatatableRequest
{
    public List<ColumnData> Columns { get; set; }

    public int Draw { get; set; }

    public bool SaveExcel { get; set; }

    public int Length { get; set; }

    public int Start { get; set; }

    public List<Order> Order { get; set; }

    public List<Search> Search { get; set; }
}

public class ColumnData
{
    public string Name { set; get; }
    public string Data { set; get; }
    public bool Searchable { set; get; }
    public bool Orderable { set; get; }
}

public class Order
{
    [JsonProperty(PropertyName = "column")]
    public int ColumnIndex { set; get; }

    [JsonProperty(PropertyName = "dir")]
    public string Direction { set; get; }
}

public class Search
{
    [JsonProperty(PropertyName = "value")]
    public string Value { set; get; }

    [JsonProperty(PropertyName = "regex")]
    public bool Regex{ set; get; }
}
  • Related