04 view models

9
View models Demystified 1

Transcript of 04 view models

Page 1: 04 view models

View models Demystified

1

Page 2: 04 view models

A model is a software representation of a real world object or API that we want to work with

� a.k.a. – A class!

2

Page 3: 04 view models

Remember, the controller creates the model and passes it to the view

Surfer

Controller

Model

View

Page 4: 04 view models

Passing a model to the view looks like this:

public ActionResult ShowPerson() { var p = new Person() { FirstName = "Amy", MiddleName = "Farrah", LastName = "Fowler", Occupation = "Neurobiologist" }; return View(p); }

4

Page 5: 04 view models

Suppose we have this page

� What would our model look like?

�  It's got task-related things �  It's got task-independent

things

5

Page 6: 04 view models

We have several options 1.  Force our task class to have

non-task things 2.  Force our non-task classes to

also store task-related things 3.  Pass two or more models to

the view 4.  Create a third class that has

a task and other non-task related things

6

Page 7: 04 view models

A class that is built to work in a view is a ViewModel public class UpdateTaskViewModel!{! public int TaskId { get; set; }! public int? TaskCategoryId { get; set; }! public string Notes { get; set; }! public TaskStatus? Status { get; set; }! public DateTime? StartDTime { get; set; }! public DateTime? StopDTime { get; set; }! public Boolean? Billable { get; set; }! public List<SelectListItem> Categories { get; set; }! public List<SelectListItem> Statuses { get; set; }! public int? Duration { get; set; }! public List<Material> Materials { get; set; }!}!

7

Page 8: 04 view models

Hands-on view model

Page 9: 04 view models

Conclusion � View models are appropriate when you have

disparate data that needs to be displayed in the view � You create a class that holds all the disparate data

and use that class as the model for the strongly-typed view

9