This article is currently in the process of being translated into Chinese (~1% done).
模板委托
Razor中的模板委托功能使你能够定义一条前端标记代码,然后用它来表示当前页面上的一个指定对象。这是个很好的工具,当你需要在你的视图中的多个地方展示你的类,你就会用到它。使用模板委托,可以帮助你从视图的大量前端标记中剥离逻辑代码,这会使阅读和维护大型视图的代码变得更容易。
在定义模板委托时,你将使用一个Func类型的委托——看起来像这样:
Func<dynamic, object> movieTemplate = @<div>@item.Title [@item.ReleaseDate.ToShortDateString()]</div>;
In this first half, before the equal-sign, I create the movieTemplate delegate. In the second part, I specify the markup template to be used. Notice that I use a variable called item - it's passed into the delegate and the type is dynamic, meaning that I can access members on it (e.g. Title) which are not checked at compile-time. Instead, they are validated at runtime, where they are expected to exist on the object passed to the delegate - if not, an exception will be thrown! I intend on passing in objects of the type Movie, a simple class we used previously in this tutorial:
public class Movie
{
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
}
So, with our templated delegate in place, we can now use it, e.g. inside a loop. Notice how I can now just call the delegate and pass in the Movie object, instead of defining the markup inside the loop:
@foreach(var movie in movies)
{
@movieTemplate(movie)
}
When populating the movies collection, used in the loop, with some test data, the generated output will look like this:
<div>The Godfather [24-03-1972]</div>
<div>Forrest Gump [06-07-1994]</div>
<div>Fight Club [15-10-1999]</div>
And here's a complete example, including test data about movies, for you to experiment with:
@using HelloMVCWorld.Models
@{
ViewData["Title"] = "TemplatedDelegate";
Func<dynamic, object> movieTemplate = @<div>@item.Title [@item.ReleaseDate.ToShortDateString()]</div>;
List<Movie> movies = new List<Movie>();
movies.Add(new Movie() { Title = "The Godfather", ReleaseDate = new DateTime(1972, 3, 24) });
movies.Add(new Movie() { Title = "Forrest Gump", ReleaseDate = new DateTime(1994, 7, 6) });
movies.Add(new Movie() { Title = "Fight Club", ReleaseDate = new DateTime(1999, 10, 15) });
}
@foreach(var movie in movies)
{
@movieTemplate(movie)
}
Summary
The templated delegates syntax found in Razor makes it easy for you to define markup-based templates which can be re-used in multiple places in your Views.