Wednesday, September 17, 2014

ASP.NET 4 MVC 4: How Views Work

---
ASPNET 4 MVC 4: How Views Work

Professional ASP.NET MVC 4 (111834846X) cover image

This tutorial is based on “Chapter 3 Views” of the book

Professional ASP.NET MVC 4

Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen, Scott Hanselman
ISBN: 978-1-118-34846-8
Paperback
504 pages
October 2012
STEPS
1) How Does The View Relate To The Control?
2) Use of variables in Control and View
3) Overriding the default View name.

STEPS

1) How Does The View Relate To The Control?

The View is related to The Control through the Name Convention. i.e, by default, Index method in Controllers/HomeController.cs will call the Views/Home/Index.cshtml.

2) Use of ViewBag Object in Control and View

Refer HomeController.cs (Line no.13)
What is ViewBag?
It is an object used for passing values between Control and View. (Read further here, http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbase.viewbag(v=vs.118).aspx )
Look at the source codes below(HomeController.cs and Index.cshtml)
HomeController.cs:Line 13 sets the value of ViewBag.Message.
Index.cshtml:Line 9 outputs the value of ViewBag.Message.
As a result, the View will display “Hello MVC” because the Message property has been set with that text in the Controller class.
What does @ mean?
Refer Index.cshtml:Line 9. It is a part of Razor Syntax, read further here, http://www.w3schools.com/aspnet/razor_syntax.asp )

3) Overriding the default View name.

Default name for the view can be overridden by specifying the alternative name in the Controller class.
3-1) Locate the statement “return View()” (line no. 15)
3-2) Replace the statement with the following:
return View("OtherName");
3-3) Add a new View.
3-4) Specify View Name, i.e., “OtherName”
3-5) Add statement “This is @ViewBag.Message” (refer line no.6 below)
3-6) Run
---

---

No comments:

Post a Comment