My main model, called Project, has two variables of type Address which is a class I defined. Since I wanted dynamic formatting of addresses based on which fields were defined. The code for my DisplayTemplate is:
@model ProjectClearanceApp.Models.Project.Address
@{
string addr = "";
if (!String.IsNullOrEmpty(Model.Line1))
{
addr += (Model.Line1 + "\n");
}
if (!String.IsNullOrEmpty(Model.Line2))
{
addr += (Model.Line2 + "\n");
}
if (!String.IsNullOrEmpty(Model.City))
{
addr += Model.City;
}
if (!String.IsNullOrEmpty(Model.State))
{
addr += (", " + Model.State);
}
if (Model.ZipCode != 0)
{
addr += (", " + Model.ZipCode);
}
Html.Raw(addr);
}
The reason I'm using a string variable and appending to it is because I originally had my display template defined as:
@model ProjectClearanceApp.Models.Project.Address
@if (!String.IsNullOrEmpty(Model.Line1))
{
@Html.DisplayFor(model => model.Line1)
<br />
}
@if (!String.IsNullOrEmpty(Model.Line2))
{
@Html.DisplayFor(model => model.Line2)
<br />
}
@if (!String.IsNullOrEmpty(Model.City))
{
@Html.DisplayFor(model => model.City)
}
@if (!String.IsNullOrEmpty(Model.State))
{
@:, @Html.DisplayFor(model => model.State)
}
@if (Model.ZipCode != 0)
{
@:, @Html.DisplayFor(model => model.ZipCode)
}
but because the last three DisplayFor's are on separate lines (at least that's my thought, I could be wrong), the addresses would display as FakeCity , FakeState , 12345 with a space before each comma (if someone has a quick fix for that, that would solve all my problems).
However when I use the string it just does not display the variable at all on my page. I set a breakpoint on the last line (Html.Raw(addr);) and addr has the correct value when my code gets to that point in processing the addresses, but when it renders the page itself, nothing shows up. I've tried Html.Display(addr); and Html.DisplayText(addr); but still no luck.