Home

Sunday, 10 July 2016

Sample Application Using View Model and Controller With Asp.net MVC

Step 1- Add Controller in Application Keep name as StudentController. Paste Below Code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TsetMVC.Models;
namespace TsetMVC.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            var empyeeList = new List<Employee>{
                            new Employee() { empId = 1, employeeName = "ravi", age = 12 } ,
                            new Employee() { empId = 2, employeeName = "pankaj", age = 25 } ,
                            new Employee() { empId = 3, employeeName = "dilip", age = 26 } ,
                            new Employee(){ empId = 4, employeeName = "amar", age = 25 } ,
                            new Employee(){ empId = 5, employeeName = "umesh", age = 34 } ,
                            new Employee(){ empId = 6, employeeName = "Pawan", age = 21 } ,
                            new Employee(){ empId = 7, employeeName = "Rajan", age = 27 } ,
                        };
            // Get the students from the database in the real application

            return View(empyeeList);
        }
}

Step 2-Create a Model Class and keep name as Student in Model Folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TsetMVC.Models
{
    public class Employee
    {
        public int empId { get; set; }
        public string employeeName { get; set; }
        public int age { get; set; }
    }
}
Step 3-After that add View in View Folder and Write Below code in Index.cshtml.
 
@model IEnumerable<TsetMVC.Models.Employee>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.employeeName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.age)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.employeeName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.age)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.empId }) |
                @Html.ActionLink("Details", "Details", new { id = item.employeeName }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.empId })
            </td>
        </tr>
    }
</table>
Step 4- After completed Above step build and run application and type below URL
http://localhost:64484/Employee/Index

 Where localhost:64484 is a your Machine host name with Port No.

Step 5 After Completion of above step  below output Came.

No comments:

Post a Comment