Reputation: 396
I want to create a search page for my database and want to search based on different conditions,
see the image:
means I have multiple textboxes and dropdowns in search page
for example if textbox1 is the search box for searching projects name and textbox2 is the search box for project date and dropdown is for searching locations
if some one wants he can put multiple conditions to search or he can only search by one condition the default it should display all records.
how can I have such a linq query
my query is currently like blow that brings all records from table Projects:
var query = (from c in db.Projects orderby c.ProjectId descending select c).AsEnumerable().Skip(starting).Take(2);
any help will be appreciated.
my search controller function:
public ActionResult get_search()
{
string Project_name = "";
if(Request.Form["project_name"]!=null)
{
Project_name = Request.Form["project_id"];
}
int Pro_id = 0;
if(Request.Form["project_id"]!=null)
{
Pro_id = Convert.ToInt32(Request.Form["project_id"]);
}
int starting = 0;
if (Request.Form["starting"] != null)
{
starting = Convert.ToInt32(Request.Form["starting"]);
}
string strpost = "&ajax=1";
strpost += "&project_id=" + Pro_id;
var q_total = (from c in db.Projects select c);
var d = "where == 1";
//var query = from c in db.Projects.Take(2).Skip(2) orderby c.ProjectId descending select c;
var query = (from c in db.Projects orderby c.ProjectId descending select c).AsEnumerable().Skip(starting).Take(2);
if(Request.Form["project_name"]!=null)
{
query = query.Where(w => w.ProjectName.Contains(Request.Form["project_name"]));
}
int numrows = q_total.Count();
//int count = data.Count;
string links = Pagination.paginate(numrows, starting, 3, "", "page", strpost);
ViewBag.link = links;
ViewBag.query = query;
return View();
}
Upvotes: 1
Views: 2744
Reputation: 9054
Very simple way:
var query = from c in db.Projects where((string.IsNullOrEmpty(pname)? true : c.ProjectName.Contains(pname))) orderby c.ProjectId descending select c;
Upvotes: 2
Reputation: 12334
You can just check for your clause and add the Where
:
var query = db.Projects.AsQueryable();
if (!string.IsNullOrWhitespace(projectName))
{
query = query.Where(w => w.Name == projectName);
}
if (date != null)
{
query = query.Where(w => w.Date == date);
}
return query.ToList();
Upvotes: 2