models、controllers、view、ViewModel、ListViewModel、BusinessLayer
1.models
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace school.Models { public class student { public string FristName { get; set; } public string LastName { get; set; } public string Height { get; set; } } }
2.controllers
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using school.BusinessLayer; using school.Models; using school.ViewModels; namespace school.Controllers { public class studentController : Controller { // // GET: /student/ public ActionResult Index() { studentListViewModel stuListVM = new studentListViewModel(); studentBusinessLayer stuBL = new studentBusinessLayer(); List<student> students = stuBL.GetStudent(); List<studentViewModel> stuVMs = new List<studentViewModel>(); foreach (student stu in students ) { studentViewModel stuVM =new studentViewModel(); stuVM.name = stu.FristName + "" + stu.LastName; stuVM.Height = stu.Height; stuVMs.Add(stuVM); } stuListVM.students = stuVMs; return View("student", stuListVM); } } }
3.view
@using school.ViewModels @model school.ViewModels.studentListViewModel <h2>student</h2> <table border="1"> <thead> <tr> <th>名字</th> <th>身高</th> </tr> </thead> <tbody> @foreach (studentViewModel item in Model.students) { <tr> <td>@item.name</td> <td>@item.Height</td> </tr> } </tbody> </table>
4.ViewModel
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace school.ViewModels { public class studentViewModel { public string name { get; set; } public string Height { get; set; } } }
5.ListViewModel
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace school.ViewModels { public class studentListViewModel { public List<studentViewModel> students{get; set; } } }
6.BusinessLayer
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using school.Models; using school.ViewModels; namespace school.BusinessLayer { public class studentBusinessLayer { public List<student> GetStudent() { List<student> stus =new List<student>(); student stu = new student(); stu.LastName = "李"; stu.FristName = "四"; stu.Height = "125"; stus.Add(stu); stu = new student(); stu.LastName = "张"; stu.FristName = "三"; stu.Height = "125"; stus.Add(stu); stu = new student(); stu.LastName = "王"; stu.FristName = "五"; stu.Height = "125"; stus.Add(stu); stu = new student(); stu.LastName = "赵"; stu.FristName = "六"; stu.Height = "125"; stus.Add(stu); return stus; } } }