Mark Tabor

Mark Tabor

  • 589
  • 2k
  • 460.1k

searching with multiple columns using entity framework in mv

Dec 2 2019 4:30 AM
Hi I have  courses table and its listing on index view , each course contains name,Program,block,Module and year , the listing is working fine now I want to search the courses based on any combinaiton of these parameters so below is my searching fields 
 the Program populates Years dropdown and the year dorpdown populates Blocks dropdown and the blocks dropdown populates Modules . Below is my intext method it works well if i give the course name string as parameter but if i just want to find all courses in specific program OR Year OR block OR Module then it returns nothing below is my controller.
public ActionResult Index(string sortOrder, string currentFilter, string SearchString,int? Block_Id,int? Program_Id,int? Year,int? Module_id, int? page)
{
ViewBag.Block_Id = new SelectList(db.Blocks, "Id", "Name");
ViewBag.Course_Category_Id = new SelectList(db.Courses_Category, "Id", "Category_Name");
ViewBag.Module_Id = new SelectList(db.Moduels, "Id", "Name");
ViewBag.Program_Id = new SelectList(db.Programs, "Id", "Program_Title");
ViewBag.Year = new SelectList(db.Years, "Id", "Name");
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (SearchString != null)
{
page = 1;
}
else
{
SearchString = currentFilter;
}
ViewBag.CurrentFilter = SearchString;
var course = from s in db.Courses
select s;
if (!String.IsNullOrEmpty(SearchString) || Block_Id != null || Program_Id != null || Year != null || Module_id != null)
{
course = course.Where(s => s.Course_Name.Contains(SearchString) || s.Program_Id==Program_Id || s.Block_Id == Block_Id || s.Module_Id==Module_id);
}
switch (sortOrder)
{
case "name_desc":
course = course.OrderByDescending(s => s.Course_Name);
break;
case "Date":
course = course.OrderBy(s => s.Date_Created);
break;
case "date_desc":
course = course.OrderByDescending(s => s.Date_Created);
break;
default:
course = course.OrderBy(s => s.Course_Name);
break;
}
int pageSize = 5;
int pageNumber = (page ?? 1);
ViewData["UserName"] = _ILogin.GetUserNamebyUserID(Convert.ToInt32(Session["UserID"]));
return View(course.ToPagedList(pageNumber,pageSize));
}
 any one can share the complete search example with multiple columns few string parameters and few integer parameters

Answers (6)