What is Models in MVC.
You might see lot of definitions for Models in MVC.
This will be interesting.
Model is nothing but a creation of property class
for the member functions. We can directly add class and define all the entities
in it. Else, we can Add Entity models directly from the Database using Entity
framework. It will just bring your database structure to the .edmx file.so it’s
also called as mirror of database design.
Ø Open
new project and Create MVC Application,
Ø Right
click on the Models and create new class as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ModelsExample.Models
{
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
}
Ø On
controller’s folder Right Click and create new controller by maintaining
Controller at the end. Here my controller is named as ‘EmployeeController’
Ø Add
model reference in the namespace section of controller, this will be helpful to
access the models in controller.
Below is my controller
code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ModelsExample.Models;
namespace ModelsExample.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Details()
{
Employee employee = new Employee()
{
EmployeeID=101,
Name="Rajamouli",
City="Hyderbad",
Gender="Male"
};
return View(employee);
}
}
}
Ø Right
click on Controller action and create the view it. Maintain the same name as it
generated the Action Result name.
To
access the models in the View,
·
we need to create the Strongly typed
View.
·
We need to return Model in the view from
the action result
View code.
@model ModelsExample.Models.Employee
@{
ViewBag.Title = "Employee Details";
}
<h2> Employee Details</h2>
<span>Employee City : </span> @Model.City
<br />
<span>Employee Name :</span>@Model.Name <br />
<span>Employee Id :</span>@Model.EmployeeID<br />
<span>Gender : </span>@Model.Gender
Ø Output
will be Like: