Business Objects as Model in ASP.NET MVC

Business Objects as Model in ASP.NET MVC

In this article and the next few, I will be discussing Business Objects as Models in an ASP.NET MVC application. If you haven't already, I recommend reading our last three articles, where we explored how to use Entity Framework and utilize entities as models.

The entities are mapped to the database tables, and object-relational mapping (ORM) frameworks like Entity Framework, NHibernate, etc., are used to retrieve and save data into a database. The business object contains both state (data) and behavior, which includes logic specific to the business. Let us now understand how to use Business Objects as a Model in an ASP.NET MVC application.

Create an Empty ASP.NET MVC Application:

Start by creating an Empty MVC Application named MVC_DEMO. After setting up the application, add a new controller named HomeController inside the Controllers folder. Then, copy and paste the following code into it.


namespace MVC_DEMO.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            ViewData["Countries"] = new List<string>()
            {
                "India",
                "US",
                "Canada",
                "Brazil"
            };
            return View();
        }
    }
}
                                        

The following URL will call the Index() action method of the HomeController. Notice that the HomeController class is inherited from the base Controller class, which in turn derives from the ControllerBase class. The ControllerBase class further inherits from the IController interface.

http://localhost:53657/Home/Index

The return View() statement inside the Index action method, by default, searches for a view named "Index" within the /Views/Home/ and /Views/Shared/ folders. If a view with the name "Index" is not found, an error will be displayed.


So, in an ASP.NET MVC application, there are several conventions that must be followed. For example, **controllers** should have the word Controller in their name and must implement the IController interface, either directly or indirectly. **Views** should be stored in specific locations where MVC can locate them.

But with models, there are no strict rules. In fact, the "Models" folder is optional, and models can be placed anywhere within the application. They can even exist in a separate project. Now, let's focus on using business objects as the model. For this demonstration, we will be using the Employee table.

Step1: Create the Required Database

Please use the SQL script below to create and populate the Employee table with sample data. Additionally, we will create a stored procedure to retrieve employee data.


-- Create Employee Table
Create table Employee
(
  Id int Primary Key Identity(1,1),
  Name nvarchar(50),
  Gender nvarchar(10),
  City nvarchar(50),
  Salary decimal(18,2),
  DateOfBirth DateTime
)
GO
-- Insert some test data into Employee table
Insert into Employee values('Akif','Male','Mumbai',4000,'02/03/1977')
Insert into Employee values('Laeeque','Male','Hyderabad',5000,'04/06/1979')
Insert into Employee values('Anam','Female','Bangalore',1000,'01/05/1979')
Insert into Employee values('Shaista','female','Hyderabad',2000,'03/07/1981')
Insert into Employee values('Noorain','female','Mumbai',3000,'02/04/1978')
Insert into Employee values('Arshiya','Female','Bangalore',4000,'02/03/1974')
Insert into Employee values('Mubin','Male','Hyderabad',5000,'04/06/1972')
Insert into Employee values('Muqeem','Male','Bangalore',6000,'07/05/1975')
Insert into Employee values('Hina','Female','Mumbai',3000,'09/08/1976')
GO
--Stored procedure to retrieve data 
Create procedure spGetAllEmployees
as
Begin
  Select Id, Name, Gender, City, Salary, DateOfBirth 
  from Employee
End
GO
                                        

Step2: Add a Class Library project with Name=”BusinessLayer” to the Solution

Right-click on the Solution Folder => Add => New Project as shown in the below image.

In the New Project window, select Visual C# from the Installed Templates on the left pane. Then, choose the Class Library template from the middle pane. Enter the name as BusinessLayer and click OK, as shown in the image below.

This will add the BusinessLayer class library project to the existing solution.

step3:Adding Models to the Class Library Project

Right-click on the BusinessLayer class library project and add a new class file named Employee.cs. After creating the Employee class, copy and paste the following code into it. This class is simple and contains six properties.


namespace BusinessLayer
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public decimal Salary { get; set; }
        public DateTime DateOfBirth { get; set; }
    }
}
                                        

step4:Adding Required References

Right-click on the References folder of the BusinessLayer class library project and add a reference to theSystem.Configuration assembly. This is necessary because we need to read the connection string from the web.config file using the ConfigurationManager class, which belongs to the System.Configuration namespace.

step5:Adding EmployeeBusinessLayer class

Right-click on the BusinessLayer class library project and add a new class file named EmployeeBusinessLayer.cs. After creating the EmployeeBusinessLayer class, copy and paste the following code into it. In this class, we define a method called GetAllEmployees(), which retrieves employee details from the database. The code is self-explanatory, so refer to the comment lines for better understanding.


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BusinessLayer
{
    public class EmployeeBusinessLayer
    {
        public List<employee> GetAllEmployess()
        {
            //Reads the connection string from web.config file. The connection string name is DBCS
            string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            //Create List of employees collection object which can store list of employees
            List<employee> employees = new List<employee>();
            //Establish the Connection to the database
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                //Creating the command object by passing the stored procedure that is used to
                //retrieve all the employess from the tblEmployee table and the connection object
                //on which the stored procedure is going to execute
                SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);
                //Specify the command type as stored procedure
                cmd.CommandType = CommandType.StoredProcedure;
                //Open the connection
                con.Open();
                //Execute the command and stored the result in Data Reader as the method ExecuteReader
                //is going to return a Data Reader result set
                SqlDataReader rdr = cmd.ExecuteReader();
                //Read each employee from the SQL Data Reader and stored in employee object
                while (rdr.Read())
                {
                    //Creating the employee object to store employee information
                    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();
                    employee.Salary = Convert.ToDecimal(rdr["Salary"]);
                    employee.DateOfBirth = Convert.ToDateTime(rdr["DateOfBirth"]);
                    //Adding that employee into List of employees collection object
                    employees.Add(employee);
                }
            }
            //Return the list of employees that is stored in the list collection of employees
            return employees;
        }
    }
}
                                        

step6:Adding a Reference to class Library Project in ASP.NET MVC Application:

Right-click on the References folder of the MVC_DEMO project and add a reference to the BusinessLayer class library project. Next, add a connection string with the name DBCS in the Web.Config file, as shown below.


<connectionstrings>
            <add name="DBCS"
            connectionstring="Data Source=LAPTOP-2HN3PT8T\SQLEXPRESS;Initial Catalog=MVC_DB;Integrated Security=True"
            providername="System.Data.SqlClient" />
</connectionstrings>
                                        

step7:Creating Controller

Right-click on the Controllers folder and add a new controller named EmployeeController. After creating the controller, copy and paste the following code into it. In this controller, there is only one action method, Index. This method creates an instance of the EmployeeBusinessLayer class and calls the GetAllEmployees() method to retrieve the list of employees. The retrieved list is then passed to the Index view.


using BusinessLayer;
using System.Collections.Generic;
using System.Web.Mvc;
namespace MVC_DEMO.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
            List<employee> employees = employeeBusinessLayer.GetAllEmployess();
            return View(employees);
        }
    }
}
                                        

step8: Adding Index View

In the EmployeeController class, right-click on the Index() action method and choose Add View from the context menu. Configure the settings as needed.

View name = Index
Model class = Employee (BusinessLayer)
Template = List
Click on the “Add” button as shown below
Change the RouteConfig.cs as shown below

We are setting the controller as Employee and the default action method as Index.


namespace MVC_DEMO
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
                                           

Set MVC_DEMO as the startup project and start the application. Then, go to http://localhost:54094/Employee/Index in the browser. The expected output should be displayed as shown in the image below.

In the next article, I will discuss FormCollection in the ASP.NET MVC application. In this article, I have explained how to use Business Objects as a Model in an ASP.NET MVC application with an example. I hope this article helps you with your requirements.