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 the IController interface either directly or indirectly. Views should be placed in a specific location where MVC can find them as.

http://localhost/projectname/Home/Index

In this example, HomeController looks at the name as.

HomeController

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

 IController interface

The controller class is inherited from the ControllerBase Class. Right-click on it and go to Definition, as given below.

ControllerBase Class

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

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

IController interface

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

Notice that we are not specifying the name of the view. How does the 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.

MVC Application

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

Views Folder

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

URL

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.

Index1.cshtml

You can see that 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 the 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.

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

Now, we will add a ClassLibrary to our project.

 ClassLibrary

Name it as a BusinessLayer.

 BusinessLayer

In SQL Server, we will create a simple store procedure, which will retrieve the data.

SQL Server

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

 Employee Class

Now, we will add another class file, 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.

public class EmployeeBusinessLayer 
{
    public IEnumerable<Employee> Employees 
    {
        get 
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            List<Employee> employees = new List<Employee>();

            using (SqlConnection con = new SqlConnection(connectionString)) 
            {
                SqlCommand cmd = new SqlCommand("spGetAllStudents", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                
                while (rdr.Read()) 
                {
                    Employee employee = new Employee();
                    employee.id = Convert.ToInt32(rdr["id"]);
                    employee.name = rdr["name"].ToString();
                    employee.gender = rdr["gender"].ToString();
                    employee.city = rdr["city"].ToString();
                    employees.Add(employee);
                }
            }

            return employees;
        }
    }
}

When you look at the code, it's a pretty straightforward one. We have a configuration manager class to read the connection string from our web.config file, as given below.

<connectionStrings>  
    <add name="Test" 
         connectionString="Data Source=DESKTOP-QOMPPF7;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=***********" 
         providerName="System.Data.SqlClient" />  
</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 built our SQL connection object. We are executing SQL commands, and we are using our stored procedure to get the desired output. We are opening the connection, executing our command and then looping through each row. We are converting a row to an employee object and with an 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 a reference, as given below.

Business Layer Library

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

Import the namespace of your BusinessLayer, as given below.

public class EmployeeController : Controller 
{   
    // GET: Employee   
    public ActionResult Index() 
    {   
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();   
        List<Employee> employees = employeeBusinessLayer.Employees.ToList();   
        return View(employees);   
    }   
}

As we want to return the list of employees, the next step is to add a view.

List of employees

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

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

Select Template

We successfully retrieved the information from the database.

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

Create New

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


Similar Articles