Template Basics

As mentioned on the previous page, all the data needed by the templates must be put in the ViewDataDictionary prior to being rendered. The ViewEngine takes everything from the calling controller's ViewData dictionary and populates the data container of the template. In addition, the engine will add the HttpContext to the container so it's accessible within the template.

ViewData Objects

Items in the ViewData dictionary can be accessed by placing them between dollar signs.

ViewData["message"] = "Employee Detail Page";
ViewData["employee"] = new { Id = 1, Name = "John Doe" };
<h1>$message$</h1>
<div>$employee.name$ has an Id of $employee.id$</div>

As you can see, the template engine doesn't care about type, or case. It just calls ToString() on the last property in the qualifier and renders it.

Conditional Statements

Conditions can only evaluate true or false. Thus, you cannot say things like if(employee.username == "super.user"), etc. This may seem like a huge missing feature, but it's actually an excellent way to enforce model-view separation. With the UI only understanding true or false, it makes it so you're not hardcoding ids, values, and other general business logic into your templates. Rather than if(employee.username == "super.user"), you could create a ViewData variable called "IsSuperUser" and set it to true. This way, the template doesn't know what constitutes a "super user", it only knows to turn sections of the page on and off.

ViewData["IsSuperUser"] = true;
<div>

	Employee Detail: 
	$if(IsSuperUser)$ 
		<a href="/allowEdit">Edit</a> 
	$else 
		Editing not allowed 
	$endif$ 
</div>

Note: You can also test for negative conditions (i.e. if(!condition)).

Iteration

You can iterate over collections located in the ViewData. Here's the format.

var employee1 = new { Id=1, Name="Joe" };
var employee2 = new { Id=2, Name="Sally" };
ViewData["employees"] = new object[] { employee1, employee2 };
<ul> 
	$employees:{ 
		<li>$it.name$ has an ID of $it.id$</li> 
	}$ 

</ul>

Notes:

  • A variable called "it" will automatically be created for a collection. You can override this by putting the following:

    $employees:{ employee | $employee.name$ has an Id of $employee.id$ }$
  • You can call other templates inside of a loop.

< Prev Next >