Step1 : Create Model Class – Right click on models folder and add class , give its name Employee
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FirstExample.Models
{
public class Employee
{
public int empid { get; set; }
public string emp_name { get; set; }
public string emp_address { get; set; }
}
}
Step2 : Create Home Controller.Pass reference of Models folder into controller namespace block.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FirstExample.Models;
namespace FirstExample.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//Initialize Employee Class using object initializers
var emp = new Employee
{
empid=1,
emp_name=”yogesh”,
emp_address=”Pratap Nagar”
};
return View(emp);
}
}
}
Step 3: Add view at Index Action.
@model and @Model look similar but they are very different. @model occurs only once and specifies the data type of the model. @Model allows you to reference the value for the model passed to the view.
@model FirstExample.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>Index</title>
</head>
<body>
<div>
<p>@Model.empid</p>
<p>@Model.emp_name</p>
<p>@Model.emp_address</p>
</div>
</body>
</html>
Output