Hi everyone,
I'm working on a grid that needs different type of filtering. For example: I've an hierarchical departments table and when i choose a parent department, grid should show me all students under the children departments. I've spent hours on this and figured it out.
Extension Method
I'm working on a grid that needs different type of filtering. For example: I've an hierarchical departments table and when i choose a parent department, grid should show me all students under the children departments. I've spent hours on this and figured it out.
Extension Method
:
public
static
class
Extensions
{
public
static
List<FilterDescriptor> ToFilterDescriptor(
this
IList<IFilterDescriptor> filters)
{
var result =
new
List<FilterDescriptor>();
if
(filters.Any())
{
foreach
(var filter
in
filters)
{
var descriptor = filter
as
FilterDescriptor;
if
(descriptor !=
null
)
{
result.Add(descriptor);
}
else
{
var compositeFilterDescriptor= filter
as
CompositeFilterDescriptor;
if
(compositeFilterDescriptor!=
null
)
{
result.AddRange(compositeFilterDescriptor.FilterDescriptors.ToFilterDescriptor());
}
}
}
}
return
result;
}
}
In Use:
public
ActionResult List([DataSourceRequest] DataSourceRequest request)
{
var departments=
new
List<
int
?>();
var nRequest =
new
DataSourceRequest
{
Groups = request.Groups,
Aggregates = request.Aggregates,
Page = request.Page,
PageSize = request.PageSize,
Sorts = request.Sorts,
Filters =
new
List<IFilterDescriptor>()
};
if
(request.Filters.Any())
{
foreach
(var fdc
in
request.Filters.ToFilterDescriptor())
{
switch
(fdc.Member)
{
case
"DepartmentId"
:
var department = Convert.ToInt32(fdc.Value);
departments.AddRange(db.StoredProcedureToTakeDepartmentsTree(department).Select(o => o.Id));
break
;
default
:
nRequest.Filters.Add(
new
FilterDescriptor
{
Member = fdc.Member,
MemberType = fdc.MemberType,
Operator = fdc.Operator,
Value = fdc.Value
});
break
;
}
}
}
if
(!departments.Any())
{
//departments = default departments if it's empty
}
var model = db.Students.Where(o => departments.Contains(o.DepartmentId))
.Select(o =>
new
{
o.Id
//Some columns
})
return
Json(model.ToDataSourceResult(nRequest), JsonRequestBehavior.AllowGet);
}
I hope it helps...
Best Regards
Hi Kerem,
I use your solution to remove one filter out of the request.filters, but then the structure of the nRequest.filters are changed.
The CompositeFilterDescriptor is removed and there is only a list left of FilterDescriptors.
ToDataSourceResult(nRequest) accept this but what is the effect of this filters for the result?
Regards, Reinier Pechler