0

I have this model:

public class DefinitionListModel : List<DefinitionListItemModel>
{
}

Then I have this display template (partial view) setup for it in DisplayTemplates:

@model Company.Product.Models.DefinitionListModel

<dl>
@foreach (var definition in Model)
{
    Html.DisplayFor(m => definition);
}
</dl>

Which calls this default display template because each item is a DefinitionListItemModel:

@model Company.Product.Models.DefinitionListItemModel

@Html.DisplayFor(m => m.Term, "DefinitionTerm");
@Html.DisplayFor(m => m.Description, "DefinitionDescription");

And the DefinitionTerm template looks like this:

@model object

@{
    if (Model != null)
    {
        string s = Model as string;
        if (s != null)
        {
            <dt>@s</dt>
        }
        else
        {
            // Other types and models that could be used.

            // Last resort.

            <dt>@Model.ToString()</dt>
        }
    }
}

A breakpoint placed in the last template is hit successfully and the view and mark-up appears to run through just fine, but none of it renders, not even the DL tag from the first template above.

Why does it hit breakpoints but not render any HTML?

2 Answers 2

2

It was all to do with semi-colons. It seems I can't just call Html.DisplayFor like a normal C# method with a semi-colon terminator.

For example, here's the revised DefinitionListModel template:

@model AcmeCo.Hudson.Models.DefinitionListModel

@if (Model != null)
{
    <dl>
        @foreach (var definition in Model)
        {
            @Html.DisplayFor(m => definition)
        }
    </dl>
}

Note the bizarre use of @ within a code block that's already C#. I assume there's a proper way to do DisplayFor from within a C# block but I don't know what it is.

Sign up to request clarification or add additional context in comments.

1 Comment

hi, will this also work with Edit Model? or do I need to reflect on the dataType?
0

It's not because of the semicolon, it's because of the missing @. This is how Razor works. What's between curly brackets is not supposed to be C#. The Razor parser tries to figure out what's code and what's content. To begin a piece of code you have to set the @ character. The Razor parser identifies everything between braces as content.

Check out Scott's blog for some very good examples.

3 Comments

I don't think that's right, but I'll wait for some votes to come in.
Why not? Have you checked out Scott's blog? What are your concerns?
Well, simply because I use code all the time that has immediately more C# in the braces of an if block in a Razor view.

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.