View Fundamentals 1
May 29, 2015
View Fundamentals
1
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
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
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
Hands-on view rendering
Passing data to the view 1. ViewData 2. ViewBag 3. Use strongly-typed views
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
ViewBag is a Dynamic object � In controller action: ViewBag.Greeting = "Hello World";!return View();!� In view: <p>@ViewBag.Greeting</p>!
Hands-on passing data to the view
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>
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); }
Hands-on strongly-typed views
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