04 view models
TRANSCRIPT
![Page 1: 04 view models](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/1.jpg)
View models Demystified
1
![Page 2: 04 view models](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/2.jpg)
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](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/3.jpg)
Remember, the controller creates the model and passes it to the view
Surfer
Controller
Model
View
![Page 4: 04 view models](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/4.jpg)
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](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/5.jpg)
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](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/6.jpg)
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](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/7.jpg)
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](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/8.jpg)
Hands-on view model
![Page 9: 04 view models](https://reader033.vdocuments.net/reader033/viewer/2022052901/556c566ad8b42acc228b491d/html5/thumbnails/9.jpg)
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