Day 9: Templates for Complex Types

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

Sites like Facebook and Twitter or any site with a “feed” often present their data in a stream of “cards” or “blocks” that are repeatable and consistent, regardless of where you see the snippet of data. Let’s take the UI we created for the Person, augment it a little bit and then make it reusable wherever we might want it displayed.

Extracting the Person Template

We’re going to build from the idea of using the DisplayTemplates in our Views\Shared folder, and add another file in there called Person.cshtml. Just right-click on the Views\Shared\DisplayTemplates folder and click Add –> View. Name the view Person, use the empty template and create it as a partial.

Now paste the following code into the file:


@model SimpleSite.Models.Person

 

<hr />
<div class=”row”>
<div class=”col-md-2”>
<img src=”http://placehold.it/150x150" />
</div>
<div class=”col-md-8”>
<h3>@Model.FirstName @Model.LastName</h3>
<p>@Model.FirstName was born on @Model.BirthDate.ToString(“D”).</p>
<p>Likes Music: @Html.DisplayFor(model => model.LikesMusic)</p>
@{
ViewBag.ListDescription = “Skills:”;
Html.RenderPartial(“StringCollection”, Model.Skills);
}
</div>
</div>

Most of this you should recognize as fairly close to the code we were using in our Index view for the simple controller. Above, I’ve added some columns and a placeholder image so that we can later give users an avatar. But I’m otherwise continuing to use the same elements we were building off of before, such as the DisplayFor and RenderPartial bits we’ve been working on.

Updating the Index View

The end result is that our Index view can be _much _simpler than it was. Here is what you need for the whole view source of Index.cshtml:

@{
ViewBag.Title = “Index”;
var likesMusic = Model.LikesMusic ? “active” : null;
var notAMusicFan = !Model.LikesMusic ? “active” : null;
}

<div class=”page-header”>
<h1>Welcome to the Person Page <small>Read all about @Model.FirstName</small></h1>
</div>

@Html.DisplayForModel(Model)

The DisplayForModel tries to find a display template that matches the type of model that is passed in, and sure enough, naming our partial view above “Person” and placing it in the Views\Shared\DisplayTemplates folder was all we needed to do to wire that up. It’s another example of “convention over configuration” at work in the MVC Framework.

Next Steps

I’ve used only one set of layout classes as styles for my person template. Later in the month we’ll explore how to make this even more reusable by introducing classes that allow the content to be rendered on different devices and screen sizes.

The placeholder image is okay, but we’d likely prefer to use an image related to the user. Tomorrow we’ll look at a way to implement an extension method that allows us to drop in a Gravatar image for any user.