We effectively have an item with three fields.

  1. Text to display in a heading.
  2. Droplink with the type of heading to display the text in (h1, h2, ...).
  3. Droplink with the heading style that points to the class(es) to add to the heading.

Based upon past experience I believed I would be able to do something like @Html.Sitecore().Field(Templates.PageText.Fields.PageTextHeading.ToString(), Model.Item, new { @class = headingStyle, EnclosingTag = headingRank }), but while the heading is properly displaying the class is not.

If I just do <div>@headingStyle</div> immediately before the above I do see the proper class name, suggesting that the values are coming across. I can also force a value to both the variable or in the anonymous object and the class still doesn't display.

Given that the heading can be variable, I don't really want to write a check to see what heading is selected just to manually add it.

Can I use Sitecore 8.2 Update-6 MVC functionality to add an enclosing tag, with a class, to the value of a text field?

  • Just for debugging purposes, have you tried putting a hardcoded value in there to see if it processes the hardcoded value? I'm wondering if the value is there but is somehow in a bad format (perhaps not enough quotation marks?) May 22 '18 at 2:26
  • 3
    did you try : @Html.Sitecore().Field(Templates.PageText.Fields.PageTextHeading.ToString(), Model.Item, new { Before = "<h1class=\"example\">", After = "</h1>" }) May 22 '18 at 3:11
  • Jay: "I can also force a value to both the variable or in the anonymous object and the class still doesn't display." Vlad: Thanks! May 22 '18 at 12:30

The reason why your code doesn't work for you:

@Html.Sitecore().Field(Templates.PageText.Fields.PageTextHeading.ToString(), Model.Item, new { @class = headingStyle, EnclosingTag = headingRank })

is that Sitecore tries to add @class attribute to the tag rendered from the field value itself, not from the EnclosingTag. If your field was a LinkField, the output would be:

<h1><a class="headingStyle">LINK_TEXT</a></h1>

Sitecore cannot add a class attribute to the text which doesn't have any html tag.

That's why the only option is what Vlad Iobagliu wrote in his comment:

var before = string.format("<{0} class=\"{1}\">", headingRank, headingStyle);
var after = string.format("</{0}>", headingRank);
@Html.Sitecore().Field(Templates.PageText.Fields.PageTextHeading.ToString(), Model.Item, new { Before = before, After = after })
  • Which explains why it worked for my link ... Thanks! May 22 '18 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.