Views in Practice

The Views folder contains the HTML files for a view. Their extension will be determined by their code.

File types commonly found in the folder include, but are not limited to the following types:

HTML .html
ASP .asp
ASP.NET .aspx
ASP.NET Razor C# .cshtml
ASP.NET Razor VB .vbhtml

One folder exists for each controller.

RAZOR VIEW ENGINE

Modifying a controller class to use a view template file creates a view. The Razor view engine is one tool for creating a view template. Some developers prefer Razor due to its clean, minimalist code and the speed of developing code for a template. There are many ways to create a template, but the general syntax used follows:

@{
	var name = “Text”; @* Comments *@
	@*
	Comments
	*@
	statement;
}
<html>
	<body>
		<center>
			<h2>Text</h2>
			<p><%Script%></p>
		</center>
	</body>
</html>

Add code by starting a block with the “@” character. Enclose code blocks in curly braces. End statements with a semicolon, enclose literal string values with double quotation marks, and enclose comments with “@*” and “*@.” Whitespace has no effect on statements.

Note that code is case sensitive; for example, two variables with the same name in different cases (e.g., “powertools” and “PowerTools”) will be treated as 2 different variables.

Review a sample document template below:

@using Payroll.UI.Repo;
@{
	ManageLink(new LinkEntry {Type = "image/x-icon", Rel = "shortcut",
		Href = Url.Content("~/design/objects/tree.ico")});
}
<!DOCTYPE html>
<html lang="en" class="static @Repo.PageClass()">
	<head>
		<meta charset="utf-8" />
		<title>@title</title>
		@Display(Model.Top)
		<%(function(elves)%>
	</head>
	<body>
		@Display(Model.Middle)
		@Display(Model.Bottom)
	</body>
</html>

LAYOUTS

Edit the _layout.cshtml file to modify a template and the general substance of a view. Typical edits include modifications to formatting, structure, and behavior; virtually identical to modifying any HTML document. Changes made to the layout file will be cloned in the _ViewStart.cshtml file. ViewBag can be used to modify the layout in use.

Review the sample layout template below:

@* Page.RegisterStyle("page.css"); *@
@{
	Model.Top.Add(Display.Top(), "8");
	Model.Top.Add(Display.TheUser(), "12");
	Model.Top.Add(Model.SiteMap, "17");
}
<div id="page">
	<header>
		@Display(Model.Top)
	</header>
	<div id="main">
		<div id="welcome">
			@Display(Model.Welcome)
		</div>
		<div id="content-wrapper">
			<div id="material">
				@Display(Model.Material)
			</div>
		</div>
		<div id="sidebar-wrapper">
			<div id="leftpane">
				@Display(Model.Leftpane)
			</div>
		</div>
	</div>
	<div id="footer-wrapper">
		<footer>
			@Display(Model.Bottom)
		</footer>
	</div>
</div>

Though view templates offer more functionality capabilities (much like CSS sheets), best practices dictate to avoid performing logic or interaction with a view template. Maintain separation of objectives to keep code clean.