Popular Posts

Sep 27, 2022

 

Searching with multiple columns using entity framework in MVC


In Controller:

public async Task<IActionResult> Index(DateTime? fromDate=null, DateTime? toDate=null, string? solvingStatusParam=null, string? priorityStatusParam=null)

        {

            var COM_CODE_LOCAL_VAR = HttpContext.Request.Cookies["COMCODE"];

            DateTime ChkDateTime = Convert.ToDateTime("02/02/2002");

            DateTime startdate = DateTime.Now;

            DateTime enddate = DateTime.Now;

            int checkdate = 0;

            if (fromDate > ChkDateTime)

            {

                startdate = Convert.ToDateTime(fromDate);

                checkdate = 1;

            }else

            {

                checkdate = 0;

            }


            if (toDate > ChkDateTime)

            {

                enddate = Convert.ToDateTime(toDate);

                checkdate = 1;

            }else

            {

                checkdate = 0;

            }

            var getTicketInfoSql = _context.ClientTicketSet.AsQueryable();

            if (checkdate==1)

            {

                getTicketInfoSql = getTicketInfoSql.Where(s => s.TicketCreateDate >= startdate && s.TicketCreateDate <= enddate);

            }

            

            if (!string.IsNullOrEmpty(solvingStatusParam))

            {

                getTicketInfoSql = getTicketInfoSql.Where(s => s.SolvingStatus.Contains(solvingStatusParam));

            }

            if (!string.IsNullOrEmpty(priorityStatusParam))

            {

                getTicketInfoSql = getTicketInfoSql.Where(s => s.ClientPriorityStatus.Contains(priorityStatusParam));

            }


            if (User.IsInRole("Client"))

            {

return View(await getTicketInfoSql.Where(a => a.IsActive == true).OrderByDescending(a => a.Id).ToListAsync());

            }

            else if (User.IsInRole("Admin"))

            {

                return View(await getTicketInfoSql.Where(a => a.IsActive == true).OrderByDescending(a => a.Id).ToListAsync());

            }

            else

            {

                return View(await _context.ClientTicketSet.OrderByDescending(a => a.Id).ToListAsync());

            }

        }



Simple Code:



var courses = db.Courses.AsQueryable();

if (!string.IsNullOrEmpty(SearchString))

{

    courses = courses.Where(s => s.Course_Name.Contains(SearchString));

}

if (Block_Id != null)

{

    courses = courses.Where(s => s.Block_Id == Block_Id);

}

if (Program_Id != null)

{

    courses = courses.Where(s => s.Program_Id == Program_Id);

}

if (Module_id != null)

{

    courses = courses.Where(s => s.Module_Id == Module_id);

}

if (Year != null)

{

    courses = courses.Where(s => s.Year == Year);

}