In ASP.NET views serve the same purpose as a page. There are no actual pages, only a view coded in HTML and another language. When a browser makes a request, the controller responds by returning a view or performing another action.
The general syntax of HTML in a view resembles any other HTML coded document. Review the typical structure of an HTML document below:
Now review the typical structure of a view:
[other manipulating code] <html> <body bgcolor="yellow"> <center> <h2>Aviation History</h2> <p><%Response.Write(Now())%></p> </center> </body> </html>
Those familiar with HTML will notice small differences in the markup above. ASP.NET has a few small requirements for the HTML in a view such as script delimiters (<% script %>). Views can contain dynamic content, and any .NET scripting language can be used for view scripts, however, Visual Basic and C# remain the most commonly used.
After the controller retrieves view state information, this information persists in a hidden form field. This storage can severely bloat the size of a page. Moving this information to the server proves a good way to ensure application stability. Perform the move by creating a class that derives from the Page class, and overrides the SavePageStateToPersistenceMedium() and the LoadPageStateFromPersistenceMedium() method. This technique not only improves reliability, but also secures data. This state data proves easy to decode and parse, which makes sensitive data extremely vulnerable.
Information can be passed from controller to view in the form of a strongly typed model object, or in the form of a dynamic type (which includes Viewbag). Strongly typed views ensure data transparency because the exact data being passed remains clear unlike using dynamic types or Viewbag. Strongly typed views also work well for complex types. Developers usually opt to employ Viewbag for passing information when design demands adding properties and spawning objects in use.
A view model offers representation of only the desired data in a view, regardless of the data. It eliminates nonessential code and validation like multiple properties when only two will be updated. It merges information from multiple sources into a single object. This not only leads to leaner code and better function, but also easily maintained and tested code. In Part 2, we will take a closer look at views.