Model in MVC in Simple Way
In MVC ‘M’ stands for Model. In MVC model is used to create logic class for any MVC application. We can put all our project logic called business logic in model in MVC.
In this example I am creating model in a simple way. In my next article I will discuss model with strongly view.
For this example I am taking controller name Home and method name is Index and create view for this index method.
To add model Right click on model folder from solution explorer ->go to add->class
Give a proper name to the class. I have given the name EmployeeData. In this class I have created some variable to store data. The code of this class is as follows:-
public class EmployeeData
public int EmpId;
public string EmpName;
public string EmpDept;
public int salary;
Now I go to the index method and create the object of this class EmployeeData and assign some data to this object and pass this object to the view as I want to show this data on this view.
public class HomeController : Controller
public ActionResult Index()
//create object of this model.
MvcApplication5.Models.EmployeeData emp = new Models.EmployeeData();
emp.EmpId = 101;
emp.EmpName = "isha";
emp.EmpDept = "Developer";
emp.salary = 12000;
//pass this object to the view
Now go to the view and create the object of this class. To create the object of any model on view we use @model.
After that use this object @model to show data on view which is as follows:-
Layout = null;
<meta name="viewport" content="width=device-width" />
As you can see that I have created a table in which in first row I have printed the column name and in second row I have showed the records using @model object which I passed to this view from index method.
The output of this code as follows:-
As you can see that it’s showing records of that object.
Note:-we must have to pass the object of model to the view otherwise it will show the error.
In my next article I will discuss same using model with strongly view.
For any query you can mail me at email@example.com