Business objects as model in MVC

Business objects as model in MVC

In this article and a few upcoming articles, I am going to discuss business objects as model in MVC application. Until now we have been using Entity Framework and entities as the model in MVC application. Entities are mapped to the database tables and object-relational mapping (ORM) frameworks like Entity Framework, NHibernate, etc. are used to retrieve and save the data into a database. The business object contains both state (data) and behavior that is logic specific to the business. 

In MVC application there are several conventions that we need to follow while working. For example, controllers need to have the word controller in them and should implement IController interface either directly or indirectly. Views should be placed in a specific location that MVC can find them. 

Let’s Create an Empty ASP.NET MVC application with the name BusinessObjectModelInMVC

Create a controller with the name as HomeController within the Controller Folder and copy and paste the below code.

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

The following URL will invoke the Index() action method within the HomeController. Notice that our HomeController inherits from base Controller class which in turn inherits from ControllerBase class. ControllerBase, in turn, inherits from IController class.

http://localhost:53657/Home/Index

the return View() statement within the HomeController by default looks for a view with name = “Index” in “/Views/Home/” and “/Views/Shared/” folders. If a view with name = “Index” is not found then we get the following error.

Business objects as model in MVC - View Error

But with models, there are no strict rules. In fact, the “Models” folder is optional and they can place anywhere within the application. They can even be present in a separate project.

Let’s now turn our attention to using business objects as the model. We will be using the table “Employee” for this demo.

Use the below SQL script to create and populate Employee table with some test 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('Pranaya','Male','Mumbai',4000,'02/03/1977')
Insert into Employee values('Anurag','Male','Hyderabad',5000,'04/06/1979')
Insert into Employee values('Priyanka','Female','Bangalore',1000,'01/05/1979')
Insert into Employee values('Subrat','Male','Hyderabad',2000,'03/07/1981')
Insert into Employee values('Sudhanshu','Male','Mumbai',3000,'02/04/1978')
Insert into Employee values('Preety','Female','Bangalore',4000,'02/03/1974')
Insert into Employee values('Sandeep','Male','Hyderabad',5000,'04/06/1972')
Insert into Employee values('Sambit','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
Step 1: Create an empty ASP.NET MVC5 application with the name MVC_DEMO
Step 2: Add a Class Library project with Name=”BusinessLayer” to the Solution

Right click on the Solution Folder => Add => New Project

Business objects as model in MVC

Select Visual C# from Installed Template

Then Select Class Library Template

Provide the name as BusinessLayer and click on OK as shown below.

Business objects as model in MVC

Now it will add BusinessLayer class library project to our existing solution as shown below

Business objects as model in MVC

Step 3: Right click on the BusinessLayer class library project and add a class file with name = Employee.cs.
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; }
    }
}

Step 4: Right-click on the “References” folder of the “BusinessLayer” class library project and add a reference to “System.Configuration” assembly.

Step 5: Right-click on the BusinessLayer class library project and add a class file with the name =EmployeeBusinessLayer.cs.
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;
        }
    }
}
Step 6: Right-click on the “References” folder of the “MVC_DEMO” project and add a reference to “BusinessLayer” project.
Step 7: Include a connection string with name = “DBCS” in Web.Config file
<connectionStrings>
    <add name="DBCS"
         connectionString="Data Source=LAPTOP-2HN3PT8T\SQLEXPRESS;Initial Catalog=MVC_DB;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
</connectionStrings>
Step 8: Right click on the “Controllers” folder and add Controller with name =”EmployeeController.cs”.
using BusinessLayer;
namespace MVC_DEMO.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
            List<Employee> employees = employeeBusinessLayer.GetAllEmployess();
            return View(employees);
        }
    }
}

Step 9: Right-click on the Index() action method in the “EmployeeController” class and select “Add View” from the context menu. Set

View name = Index

Model class = Employee (BusinessLayer)

Template = List

Click “Add” button as shown below

Business objects as model in MVC

Change the RouteConfig.cs as shown below

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 }
            );
        }
    }
}

Run the application and navigate to http://localhost:54094/Employee/Index. The output should be as shown below. 

Business objects as model in MVC

In the next article, I will discuss FormCollection in ASP.NET MVC application.

SUMMARY

In this article, I try to explain how to use Business Object as Model in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *