Iram Khan

Iram Khan

  • 1.9k
  • 51
  • 1.1k

Multiple Search in MVC

Jan 3 2018 4:35 AM
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; }

Brought to you by: JavaScript SDK for Bold BI dashboard and analytics embedding. Free trial.

Answers (3)