Using business objects as model in mvc
Suggested Videos
create one controller name as home
public class HomeController : Controller
{
public ViewResult Index()
{
ViewData["Countries"] = new List<string>()
{
"India",
"US",
"UK",
"Canada"
};
return View();
}
}
Create table Employee
(
Id int Primary Key Identity(1,1),
Name nvarchar(50),
Gender nvarchar(10),
City nvarchar(50),
DateOfBirth DateTime
)
insert 4 record
Stored procedure to retrieve data
Create procedure spGetAllEmployees
as
Begin
Select Id, Name, Gender, City, DateOfBirth
from tblEmployee
End
Step 1: Create an [Link] MVC 4 Web application with name = MVCDemo
Step 2: Add a Class Library project with Name="BusinessLayer"
Step 3: Right click on the BusinessLayer class library project, and add a class file
with name = [Link].
using System;
using [Link];
using [Link];
using [Link];
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 DateTime DateOfBirth { get; set; }
}
}
Step 4: Right click on the "References" folder of the "BusinessLayer" class library
project, and add a reference to "[Link]" assembly.
Step 5: Right click on the BusinessLayer class library project, and add a class file
with name = [Link].
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace BusinessLayer
{
public class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get
{
string connectionString =
[Link]["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);
[Link] = [Link];
[Link]();
SqlDataReader rdr = [Link]();
while ([Link]())
{
Employee employee = new Employee();
[Link] = Convert.ToInt32(rdr["Id"]);
[Link] = rdr["Name"].ToString();
[Link] = rdr["Gender"].ToString();
[Link] = rdr["City"].ToString();
[Link] = [Link](rdr["DateOfBirth"]);
[Link](employee);
}
}
return employees;
}
}
}
}
Step 6: Right click on the "References" folder of the "MVCDemo" project, and add a
reference to "BusinessLayer" project.
Step 7: Include a connection string with name = "DBCS" in [Link] file
<add name="DBCS"
connectionString="server=.; database=Sample; integrated security=SSPI"
providerName="[Link]"/>
Step 8: Right click on the "Controllers" folder and add Controller with name
= "[Link]".
public class EmployeeController : Controller
{
public ActionResult Index()
{
EmployeeBusinessLayer employeeBusinessLayer =
new EmployeeBusinessLayer();
List<Employee> employees = [Link]();
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
View engine = Razor
Select "Create a strongly-typed view" checkbox
Scaffold Template = List
Click "Add" button