Answer the question
In order to leave comments, you need to log in
Three-layer application architecture, business logic layer, how to move sorting from the controller into a separate method in the business logic?
Good morning! Many are familiar with the example of Contoso Universuty
. I build my application like this on a three-layer architecture, how do I move sorting and searching (code below) into a separate method in the business logic, and only call it in the controller?
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
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 students = from s in db.Students
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString)
|| s.FirstMidName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default: // Name ascending
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}
Answer the question
In order to leave comments, you need to log in
Good afternoon! You form a business logic layer, a data access layer. In the business logic layer, you create some kind of "business service" a la "ItemsService". In this class, you create a method with a similar signature. And transfer all the main filtering logic from the controller action method to the business service method. In the controller, you just access the business service instance and call the desired method, which does all the main work. As a result, you "put your controller on a diet" - the code in the action methods is significantly reduced, and the action methods after such operations will not know anything about the business logic. On this topic, you also immediately study the issues: IoC container (my colleagues and I prefer Autofac) and Dependency Injection.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question