Loading

ASP.NET MVC

What is Business Objects as Model in ASP.NET MVC?. The Complete ASP.NET MVC Developer Course 2022 [Videos].

In this and in few upcoming Videos, I am going to discuss Business Objects as Model in ASP.NET MVC application. Please watch our previous three Videos where we discussed how to use Entity Framework and use entities as our 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 the data into a database. The business object contains both state (data) and behavior that is logic specific to the business.  Let us understand how to use Business Objects as Model in ASP.NET MVC Application.

Create an Empty ASP.NET MVC Application:

First, create an Empty MVC Application with the name MVC_DEMOOnce you create the application, then create a controller with the name as HomeController within the Controllers Folder and then copy and paste the below code in 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 invoke the Index() action method of the HomeController. Notice that, the HomeController class is inherited from the base Controller class which in turn inherits from ControllerBase class. ControllerBase, in turn, inherits from the IController interface.

http://localhost:53657/Home/Index

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

Resource Not Found Error in ASP.NET MVC Application

So, In the ASP.NET 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 the IController interface either directly or indirectly. Views should be placed in a specific location that MVC can find them. 

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. Lets now turn our attention to using business objects as the model. We will be using the table “Employee” for this demo.

Step1: Create the Required Database 

Please use the below SQL script to create and populate the Employee table with some test data. Also, we are creating one stored procedure to retrieve the 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








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.

Adding Class Library Project in Existing Solution

From the new project window, select Visual C# from Installed Template from the left pane and then select Class Library Template from the middle pane. Provide the name as BusinessLayer and click on the OK as shown in the below image.

Understanding Business Objects as Model in ASP.NET MVC

Now it will add the BusinessLayer class library project to our existing solution.

Step3: Adding Models to the Class Library Project

Right-click on the business layer class library project and add a class file with the name Employee.cs. Once you created the Employee class then copy and paste the following code into it. The following class is very straightforward. We simply created the class with 6 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 business layer class library project and add a reference to the “System.Configuration” assembly. This is required as we want to watch the connection string from the web config file using the ConfigurationManager class and this class belongs to System.Configuration namespace.

Step5: Adding EmployeeBusinessLayer class

Right-click on the business layer class library project and add a class file with the name EmployeeBusinessLayer.cs. Once you created the EmployeeBusinessLayer class then copy and paste the following code into it. In the following class, we define one method i..e. GetAllEmployess(). This method is used to get the employee details from the database. The following code is self-explained, so please go through the comment lines.

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. Then Include a connection string with name = “DBCS” in Web.Config file as shown below.

<connectionStrings>
<add name="DBCS"
connectionString="Data Source=LAPTOP-2HN3PT8TSQLEXPRESS;Initial Catalog=MVC_DB;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Step8: Creating Controller

Right-click on the “Controllers” folder and add a Controller with the name “EmployeeController” and then copy and paste the following code into it. In the below controller we have only one action method i.e. Index. This method creates an instance of EmoloyeeBusinessLayer class and then calls the GetAllEmployees method which will return the list of employees. The list of employees is then handed over 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);
}
}
}
Step9: Adding Index View

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

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

Adding Views in ASP.NET MVC Application

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 your startup project and run the application, then navigate to http://localhost:54094/Employee/Index. It should display the output as expected as shown in the below image. 

Business Objects as Model in ASP.NET MVC Application

See All

Comments (279 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /279

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /279

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /279