0

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.

1 Answer 1

1

You need to add a leading @ to Html.Raw(). Without that your just executing the method, not returning its value and outputting the result it generates.

@model ProjectClearanceApp.Models.Project.Address
@{
    string addr = "";
    ....
    @Html.Raw(addr); // add leading `@`
}
Sign up to request clarification or add additional context in comments.

3 Comments

Even though the whole block of code is wrapped with @{ ... }?
Yes :) - did you try it?
I won't be in front of the code again until tomorrow but I'll let you know if it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.