31

The following code:

var canonical = new TagBuilder("link");
canonical.MergeAttribute("rel", "canonical");
canonical.MergeAttribute("href", url);
return new MvcHtmlString(canonical.ToString());

Creates a tag:

<link href="http://local.domain.com/" rel="canonical"></link>

Is it possible to render

<link href="http://local.domain.com/" rel="canonical"/>

instead, using TagBuilder?

Chase Florell
  • 46,378
  • 57
  • 186
  • 376
BrunoLM
  • 97,872
  • 84
  • 296
  • 452

2 Answers2

81

Have you tried:

canonical.ToString(TagRenderMode.SelfClosing);
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • I actually didn't see there were that option in `ToString`. That worked, thank you. – BrunoLM Jan 29 '11 at 23:57
  • 2
    @rock, I'm sure Bruno knows how to accept. ;) And he has to wait a little bit before he's allowed to (since he just asked it). – Kirk Woll Jan 30 '11 at 00:00
3

You can also try.

TagBuilder  tagBuilder = new TagBuilder("link");
tagBuilder.TagRenderMode = TagRenderMode.SelfClosing;
maxspan
  • 13,326
  • 15
  • 75
  • 104
  • 2
    The TagRenderMode property seems to only be available on the Asp.Net core version of TagBuilder. https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.rendering.tagbuilder.tagrendermode?view=aspnetcore-2.2 – Tikall Sep 24 '19 at 14:11