Top Banner
View Fundamentals 1
13
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 03 view fundamentals

View Fundamentals

1

Page 2: 03 view fundamentals

The View's mission is simple: show the user the model � The Controller instantiates the model and sends it to

the view. The view simply draws it �  It just has to know how to turn the model into HTML

2

Page 3: 03 view fundamentals

The View is rendered from the Controller public ActionResult Whatever()!{! return View();!}!� Assumes view name is the same as the action � Looks for it in

�  Views/ControllerName �  Views/Shared

3

Page 4: 03 view fundamentals

You can specify the name of the view and controller � Specify Action public ActionResult Whatever()!{! return View("New");!}!� Action and Controller public ActionResult Whatever()!{! return View("~/Views/Other/Other.cshtml");!}!

4

Page 5: 03 view fundamentals

Hands-on view rendering

Page 6: 03 view fundamentals

Passing data to the view 1.  ViewData 2.  ViewBag 3.  Use strongly-typed views

Page 7: 03 view fundamentals

ViewData � A dictionary<string, object> � To set in the controller ViewData["Focus"] = new Person() {! FirstName="Leslie", ! LastName="Winkle", ! Occupation="Experimental Physicist" !};!� To read in the view @{!var person = (Person) ViewData["Focus"];!}!

7

Page 8: 03 view fundamentals

ViewBag is a Dynamic object �  In controller action: ViewBag.Greeting = "Hello World";!return View();!�  In view: <p>@ViewBag.Greeting</p>!

Page 9: 03 view fundamentals

Hands-on passing data to the view

Page 10: 03 view fundamentals

Strongly-typed views �  In view, add a new top line @model Person

� … or … @model ICollection<Person>

� Then the page recognizes the properties of that class <p>Name: @Model.FirstName @Model.LastName</p>

<p>@Model.Occupation</p>

Page 11: 03 view fundamentals

We pass the model to the view public ActionResult DoSomething() {

var p = new Person() {

FirstName = "Amy",

MiddleName = "Farrah",

LastName = "Fowler",

Occupation = "Neurobiologist"

};

return View(model); }

Page 12: 03 view fundamentals

Hands-on strongly-typed views

Page 13: 03 view fundamentals

Conclusion � The controller generates data to present to the user �  It presents that through the view � So we must get data from the controller to the view

through �  ViewData �  ViewBag �  Strongly-typed Views

13