Tuesday, 21 January 2014

Models in MVC 4

In this article i am going to explain models in mvc.we want to retrieve an employee information from Employee table and display it as shown below.




 To encapsulate employee information I need to have an employee model class. let’s add employee model class to mvc project. Go to Models folder right click on it and change class name  as Employee and click on add. Write below code in Employee Model Class

public class Employee
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
    }


Let’s add another controller name it as Employee, actually we retrieve the employee information from the Database, but for now I am going to hard coded the employee information with in the controller.
I need to find the Employee class with in the controller but I didn’t find, so add MvcDemoApps.Models
 Here Mvcdemoapps is application name.



We need to add a view which can present the employee information to the end user. Right click on Controller action method and select add view. check the create a strongly-typed view, select Model class Employee with in dropdownlist but there is no Employee class for that build the application now it appears in Dropdownlist select Employee Model class and click on Add.

Lets change code in the Details View
@model MvcDemoApps.Models.Employee

@{
    ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>
<table>
<tr>
<td><b>Employee Id</b></td>
<td>@Model.EmpId</td>
</tr>
<tr>
<td><b>Employee Name</b></td>
<td>@Model.Name</td>
</tr>
<tr>
<td><b>Gender</b></td>
<td>@Model.City</td>
</tr>
<tr>
<td><b>City</b></td>
<td>@Model.City</td>
</tr>
</table>

Now run the application (give controller name and action method name in the controller).
You will get following error


Because we didn’t pass employee object to  view. Let’s pass employee object to view
  public ActionResult Details()
        {
            Employee objemployee = new Employee()
            {
                EmpId=200,
                Name="SriRama",
                Gender="Male",
                City="Hyderabad"
            };
            return View(objemployee);
        }
Now run the application and we get the following output.
 tags:Models in Mvc,:Models in Mvc 4,:Models in Mvc 3,:Models in asp.netMvc,:Models,:Models in Mvc