Strongly View in MVC

Strogly View

In my last article I discussed model in a simply way. In this example I am going to explain model using strongly view.
For this example I am taking the previous example in which I have created the model class named EmployeeData.

Add Model using Strongly View

In this example after creating the model class, create view where you want to use this model. So go to index method->right click on it->add view.
In this view check the option creates a strongly-typed view and selects your model from dropdownlist.
Note: - sometime it happened that model class do not show in dropdownlist. In this situation kindly build your project and then again try.
After adding this view you can see that it automatically added @model object for this class which you provided in strongly view.

Controller Class Code

Now create the object of this class in index method, assign data to the variable and then pass this object to the 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);


Code of Index View

Now go to view and use this object and show the data to the screen
 @model MvcApplication5.Models.EmployeeData

    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <table border="1">
                <th>Employee ID</th>
                <th>Employee Name</th>
                <th>Employee Dept</th>
                <th>Employee Salary</th>

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


Now execute this code and check your output which is as follows:-

No comments:

Post a Comment