Model in MVC

What is Model

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.

Add Model

To add model Right click on model folder from solution explorer ->go to add->class

Give a proper name to the class.

Model Class Code

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:-
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication5.Models
    public class EmployeeData
        public int EmpId;
        public string EmpName;
        public string EmpDept;
        public int salary;

Code of Controller

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.
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication5.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            //create object of this model. 
            MvcApplication5.Models.EmployeeData emp = new Models.EmployeeData();
            emp.EmpId = 101;
            emp.EmpName = "durgesh";
            emp.EmpDept = "Developer";
            emp.salary = 30000;

            //pass this object to the view
            return View(emp);


     <td>@Model.EmpDept  </td>
                <td>@Model.salary  </td>


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.

No comments:

Post a Comment