3
Answers

Multiple Search in MVC

Iram Khan

Iram Khan

7y
181
1
I have following fields for searching.
(1) Travel From
(2) Travel To
(3) Company Name
(4) Travel Date
I want to keep first two compulsory while last two optional. But when i add (|| operator) to company name or Travel Date, this will fetch all the records for all companies (e.g if customer selects Travel From, Travel To and Company Name by leaving the Date empty, it will show all the companies record instead of that particular company.
Here is my search code.
public IEnumerable<Vehicles> GetSearchedVehicles(SearchViewModel newSearch)
{
var result = db.Vehicle.Include(x => x.Company).Include(x => x.Route).Include(x => x.Status)
.Where(x => x.Company.Name.Contains(newSearch.CompanyName) || (string.IsNullOrEmpty(newSearch.CompanyName))
&& x.Route.TravelDate == newSearch.TravelDate ||(!newSearch.TravelDate.HasValue)
&& x.Route.TravelFrom.Contains(newSearch.TravelFrom)
&& x.Route.TravelTo.Contains(newSearch.TravelTo));
return result;
}
And here is Model.
public class SearchViewModel
{
public int? id { get; set; }
public string CompanyName { get; set; }
public string TravelFrom { get; set; }
public string TravelTo { get; set; }
public DateTime? TravelDate { get; set; }
}
Answers (3)
0
Ehsan Sajjad

Ehsan Sajjad

NA 5k 426k 7y
Please refer to the following article which explains how to add multiple columns search :
 
 http://www.c-sharpcorner.com/article/grid-view-with-server-side-advanced-search-using-jquery-datatables-in-asp-net-mv/
 
0
Pramod Thakur

Pramod Thakur

NA 7.3k 791.5k 7y
Read this article.
 
http://tomasp.net/blog/dynamic-linq-queries.aspx/
 
Mark as answer if you find helpful. 
0
Mangesh Gaherwar

Mangesh Gaherwar

NA 4.1k 70.8k 7y
Group compulsory and optional parameter in the Query
 
and or them accordingly