ASP.NET MVC View Model
I recently read an article from Stephen Walther on View Models and gave it a spin. In this example,i created two typed class namely People and address..You may create properties or public fields in there. After that,create a controller with the view model which has List properties. Then in your view,you simply inherit the PersonViewModel.
Below is the Person Controller with the PersonViewModel.
Here is the view that will utilize the PersonViewModel.
Below is the Person Controller with the PersonViewModel.
public class PersonController : Controller { public ActionResult Index() { // Create list of People var people = new List<People>(); people.Add(new People(30, "Nelson G.")); people.Add(new People(28, "James Ingram")); // Create list of Address var address = new List<Address>(); address.Add(new Address(9000, "Cebu")); address.Add(new Address(6521, "Baybay")); // Return view return View(new PersonViewModel(people, address)); } public ActionResult Details() { // Create list of People var people = new List<People>(); people.Add(new People(30, "Nelson G.")); people.Add(new People(28, "James Ingram")); // Create list of Address var address = new List<Address>(); address.Add(new Address(9000, "Cebu")); address.Add(new Address(6521, "Baybay")); // Return view return View(new PersonViewModel(people, address)); } } // View Model Classes public class PersonViewModel { public PersonViewModel(List<People> people, List<Address> address) { this.People = people; this.Address = address; } public List<People> People { get; private set; } public List<Address> Address { get; private set; } }
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewModelsDemo.Controllers.PersonViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Details </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Details</h2> <ul> <%int i = 0; %> <%foreach (var item in Model.People) %> <%{ %> <li> <%=item.Name %> <%= Model.Address[i].completeAdd %> </li> <%i++; %> <%} %> </ul> </asp:Content>
Comments
Post a Comment