Thursday 21 November 2013

Use of Model using strongly view in MVC

Use of Model using strongly view in MVC

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.

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.



Figure 1

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.

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 = "isha";
            emp.EmpDept = "Developer";
            emp.salary = 12000;

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

    }
}

Now go to view and use this object and show the data to the screen

@model MvcApplication5.Models.EmployeeData

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
  
    <table border="1">
            <tr>
                <th>Employee ID</th>
                <th>Employee Name</th>
                <th>Employee Dept</th>
                <th>Employee Salary</th>


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

</body>
</html>

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



Figure 2

in this way we can show data 

For any query you can mail me at malhotra.isha3388@gmail.com




No comments:

Post a Comment