Adding business logic layer to a project that uses model binding and web forms
This tutorial series demonstrates basic aspects of using model binding with an ASP.NET Web Forms project. Model binding makes data interaction more straight-forward than dealing with data source objects (such as ObjectDataSource or SqlDataSource). This series starts with introductory material and moves to more advanced concepts in later tutorials.
This tutorial shows how to use model binding with a business logic layer. You will set the OnCallingDataMethods member to specify that an object other than the current page is used to call the data methods.
This tutorial builds on the project created in the earlier parts of the series.
You can download the complete project in C# or VB. The downloadable code works with either Visual Studio 2012 or Visual Studio 2013. It uses the Visual Studio 2012 template, which is slightly different than the Visual Studio 2013 template shown in this tutorial.
What you’ll build
Model binding enables you to put your data interaction code in either the code-behind file for a web page or in a separate business logic class. The previous tutorials have shown how to use the code-behind files for data interaction code. This approach works for small sites but it can lead to code repetition and greater difficulty when maintaining a large site. It can also be very difficult to programmatically test code that resides in code behind files because there is no abstraction layer.
To centralize the data interaction code, you can create a business logic layer that contains all of the logic for interacting with data. You then call the business logic layer from your web pages. This tutorial shows how to move all of the code you have written in the previous tutorials into a business logic layer, and then use that code from the pages.
In this tutorial, you’ll:
- Move the code from code-behind files to a business logic layer
- Change your data bound controls to call the methods in the business logic layer
Create business logic layer
Now, you will create the class that is called from the web pages. The methods in this class look similar to the methods you used in the previous tutorials and include the value provider attributes.
First, add a new folder called BLL.
In the BLL folder, create a new class named SchoolBL.cs. It will contain all of the data operations that originally resided in code-behind files. The methods are almost the same as the methods in the code-behind file, but will include some changes.
The most important change to note is that you are no longer executing the code from within an instance of Page class. The Page class contains the TryUpdateModel method and the ModelState property. When this code is moved to a business logic layer, you no longer have an instance of the Page class to call these members. To get around this issue, you must add a ModelMethodContext parameter to any method that accesses TryUpdateModel or ModelState. You use this ModelMethodContext parameter to call TryUpdateModel or retrieve ModelState. You do not need to change anything in the web page to account for this new parameter.
Replace the code in SchoolBL.cs with the following code.
[!code-csharpMain]
1: using System;
2: using System.Linq;
3: using ContosoUniversityModelBinding.Models;
4: using System.Web.ModelBinding;
5: using System.Web.UI.WebControls;
6: using System.Data.Entity;
7: using System.Data.Entity.Infrastructure;
8:
9: namespace ContosoUniversityModelBinding.BLL
10: {
11: public class SchoolBL : IDisposable
12: {
13: SchoolContext db = new SchoolContext();
14:
15: public IQueryable<Student> GetStudents([Control] AcademicYear? displayYear)
16: {
17: var query = db.Students.Include(s => s.Enrollments.Select(e => e.Course));
18:
19: if (displayYear != null)
20: {
21: query = query.Where(s => s.Year == displayYear);
22: }
23:
24: return query;
25: }
26:
27: public void InsertStudent(ModelMethodContext context)
28: {
29: var item = new Student();
30:
31: context.TryUpdateModel(item);
32: if (context.ModelState.IsValid)
33: {
34: db.Students.Add(item);
35: db.SaveChanges();
36: }
37: }
38:
39: public void DeleteStudent(int studentID, ModelMethodContext context)
40: {
41: var item = new Student { StudentID = studentID };
42: db.Entry(item).State = EntityState.Deleted;
43: try
44: {
45: db.SaveChanges();
46: }
47: catch (DbUpdateConcurrencyException)
48: {
49: context.ModelState.AddModelError("",
50: String.Format("Item with id {0} no longer exists in the database.", studentID));
51: }
52: }
53:
54: public void UpdateStudent(int studentID, ModelMethodContext context)
55: {
56: Student item = null;
57: item = db.Students.Find(studentID);
58: if (item == null)
59: {
60: context.ModelState.AddModelError("", String.Format("Item with id {0} was not found", studentID));
61: return;
62: }
63:
64: context.TryUpdateModel(item);
65: if (context.ModelState.IsValid)
66: {
67: db.SaveChanges();
68: }
69: }
70:
71: public IQueryable<Enrollment> GetCourses([QueryString] int? studentID)
72: {
73: var query = db.Enrollments.Include(e => e.Course)
74: .Where(e => e.StudentID == studentID);
75: return query;
76: }
77:
78: private bool disposedValue = false;
79:
80: protected virtual void Dispose(bool disposing)
81: {
82: if (!this.disposedValue)
83: {
84: if (disposing)
85: {
86: db.Dispose();
87: }
88: }
89: this.disposedValue = true;
90: }
91:
92: public void Dispose()
93: {
94: Dispose(true);
95: GC.SuppressFinalize(this);
96: }
97: }
98: }
Revise existing pages to retrieve data from business logic layer
Finally, you will convert the pages Students.aspx, AddStudent.aspx, and Courses.aspx from using queries in the code-behind file to using the business logic layer.
In the code-behind files for Students, AddStudent, and Courses, delete or comment out the following query methods:
- studentsGrid_GetData
- studentsGrid_UpdateItem
- studentsGrid_DeleteItem
- addStudentForm_InsertItem
- coursesGrid_GetData
You now should have no code in the code-behind file that pertains to data operations.
The OnCallingDataMethods event handler enables you to specify an object to use for the data methods. In Students.aspx, add a value for that event handler and change the names of the data methods to the names of the methods in the business logic class.
[!code-aspxMain]
1: <asp:GridView runat="server" ID="studentsGrid"
2: ItemType="ContosoUniversityModelBinding.Models.Student" DataKeyNames="StudentID"
3: SelectMethod="GetStudents"
4: UpdateMethod="UpdateStudent" DeleteMethod="DeleteStudent"
5: AllowSorting="true" AllowPaging="true" PageSize="4"
6: AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
7: AutoGenerateColumns="false"
8: OnCallingDataMethods="studentsGrid_CallingDataMethods">
In the code-behind file for Students.aspx, define the event handler for the CallingDataMethods event. In this event handler, you specify the business logic class for data operations.
[!code-csharpMain]
1: protected void studentsGrid_CallingDataMethods(object sender, CallingDataMethodsEventArgs e)
2: {
3: e.DataMethodsObject = new ContosoUniversityModelBinding.BLL.SchoolBL();
4: }
In AddStudent.aspx, make similar changes.
[!code-aspxMain]
1: <asp:FormView runat="server" ID="addStudentForm"
2: ItemType="ContosoUniversityModelBinding.Models.Student"
3: InsertMethod="InsertStudent" DefaultMode="Insert"
4: OnCallingDataMethods="addStudentForm_CallingDataMethods"
5: RenderOuterTable="false" OnItemInserted="addStudentForm_ItemInserted">
[!code-csharpMain]
1: protected void addStudentForm_CallingDataMethods(object sender, CallingDataMethodsEventArgs e)
2: {
3: e.DataMethodsObject = new ContosoUniversityModelBinding.BLL.SchoolBL();
4: }
In Courses.aspx, make similar changes.
[!code-aspxMain]
1: <asp:GridView runat="server" ID="coursesGrid"
2: ItemType="ContosoUniversityModelBinding.Models.Enrollment"
3: SelectMethod="GetCourses" AutoGenerateColumns="false"
4: OnCallingDataMethods="coursesGrid_CallingDataMethods">
[!code-csharpMain]
1: protected void coursesGrid_CallingDataMethods(object sender, CallingDataMethodsEventArgs e)
2: {
3: e.DataMethodsObject = new ContosoUniversityModelBinding.BLL.SchoolBL();
4: }
Run the application and notice that all of the pages function as they had previously. The validation logic also works correctly.
Conclusion
In this tutorial, you re-structured your application to use a data access layer and business logic layer. You specified that the data controls use an object that is not the current page for data operations.
|