Using Business Objects As Models In MVC

Introduction

So far, we have used  Entity Framework and entities, which are mapped to the database tables, and object relational mapping tools like Entity Framework, nHibernate etc., which  are used to retrieve and save the data.

Business objects contain both state (data) and behavior, which is the logic of being specific to the business.

In MVC, there are several conventions to be followed. Example- Controllers need to have a word controller in them and should implement IController interface either directly or indirectly. Views should be placed in a specific location, which MVC can find them as-

http://localhost/projectname/Home/Index

In this example, HomeController, look at the name as-
 
HomeController

Here, it has the controller at the end of it and this HomeController is actually inheriting from Controller class, but it should implement IController interface. Now, here HomeController is indirectly inheriting from the IController interface. We will inspect that click on controller and go to definition as-

HomeController

Controller class is inheriting from ControllerBase Class. Right click on it and go to Definition, as given below-

HomeController

Notice the ControllerBase is getting inherited from IController interface, which means our HomeController class is indirectly inheriting from IController interface.

When it comes to views, we also have convention, the name of the views is important. Let’s understand practically with an example here.

HomeController

In our MVC Application, we have our HomeController. Within it, we have Index action method. This index action method is invoked, when we type in URL as /home/Index.

Notice, we are not specifying the name of the view. How does MVC Application know what view it should return? This is where the convention comes into play. MVC Application is going to inside the controller for views. At the moment, I have a view, which is Index.cshtml

cshtml

This is present within Views Folder of Home Folder. In Our View, we are looping the code, as given below-

cshtml

Let’s run our solution and type /home/Index in our URL, as given below-

cshtml

We got the desired output as expected. Now, I will rename it to Index1.cshtml, run our app and see the output, as given below-

cshtml

You can see, when I try to navigate home/Index, we get this error. It’s actually looking for Index.aspx,ascx,.cshtml and so on. It’s basically looking for a view file either with name Index.aspx and so on in the Home folder and in the Shared Folder. So if it doesn’t find a View with those names and the locations, it’s going to throw this exception.

Due to this, the conventions are very important for Controllers and Views.

NoteIn MVC, we can get rid of the Models Folder or we can delete the folder. In MVC Application, your Models can reside anywhere in the Application.

Now, we will add a ClassLibrary to our project.

cshtml

Name it as a BusinessLayer.

cshtml
 
In SQL Server, we will create a simple store procedure, which will retrieve the data as-

cshtml

Now, we will assign get and set properties in an Employee Class, as given below-

cshtml

Now, we will add another class file as EmployeeBusinessLayer in this class file. It will contain all the business logic. In this class, we will have some data access code, which will retrieve the code from the database table.
  1. publicclassEmployeeBusinessLayer {  
  2.     publicIEnumerable < Employee > Employees {  
  3.         get {  
  4.             stringconnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  5.             List < Employee > employees = newList < Employee > ();  
  6.   
  7.             using(SqlConnection con = newSqlConnection(connectionString)) {  
  8.                 SqlCommandcmd = newSqlCommand("spGetAllStudents", con);  
  9.                 con.Open();  
  10.                 SqlDataReaderrdr = cmd.ExecuteReader();  
  11.                 while (rdr.Read()) {  
  12.                     Employeeemployee = newEmployee();  
  13.                     employee.id = Convert.ToInt32(rdr["id"]);  
  14.                     employee.name = rdr["name"].ToString();  
  15.                     employee.gender = rdr["gender"].ToString();  
  16.                     employee.city = rdr["city"].ToString();  
  17.                     employees.Add(employee);  
  18.   
  19.                 }  
  20.   
  21.             }  
  22.             return employees;  
  23.   
  24.         }  
  25.   
  26.     }  
When you look at the code, its pretty straight forward one. We have a configuration manager class to read the connection string from our web.config file, as given below-
  1. <connectionStrings>  
  2.     <addnameaddname="Test" connectionString="Data Source=DESKTOP-QOMPPF7;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=***********" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
Thus, we are reading the connection string as we want the list of employees. We had created an employee object, which will return the list of the employees and then we are building our SQLconnection object. We are executing SQL command and we are using our stored procedure to get the desired output. We are opening the connection and executing our command and then loop through each row. We are converting a row to employee object and with a employee object with a list and then we are returning employees .

Now, we will add a reference to our main project. We want to consume this Business Layer Library in our main project, so kindly add reference, as given below-

<connectionStrings /> <addname="test" connectionstring= ">

Now, we will add a controller and we will call this controller as EmployeeController.

Import the namespace of your BusinessLayer, as given below-
  1. publicclassEmployeeController: Controller {  
  2.     // GET: Employee  
  3.     publicActionResultIndex() {  
  4.         EmployeeBusinessLayeremployeeBusinessLayer = newEmployeeBusinessLayer();  
  5.         List < Employee > employees = employeeBusinessLayer.Employees.ToList();  
  6.         return View(employees);  
  7.     }  
  8. }  
As we want to return the list of employees, next step is to add a view.

employees

Select Template as List and click Add. When you click Add, a view with index.cshtml creates under Employee folder inside Views folder.

In it, view a code, which has automatically created. Kindly add some styles and run the solution and you will see-

employees

We had successfully retrieved the information from the database.

When you click Create New, it will give you an error, as given below-

employees

Do we have an action method in Employee Controller as Create? NO, due to which it’s giving an error.

Next Recommended Readings