2

I want to use a string variable which could contain the values h1, h2, h3 etc to build some html. This works fine for the opening tag, but does not work nicely for the closing tag. If I write

@{ var tag = "h1" ; }
<@tag>some title here</@tag>

I end up with the html

<h1>some title here</@h1>

A work-around which seems to work is

<@tag>some title here<@("/"+tag)>

but it's pretty ugly. Is there some escape sequence I need to use here?

4
  • Would creating a custom HTML helper work? Something like @Html.MyCustomTag("h1", "some title here") using TagBuilder? Commented Sep 22, 2017 at 21:46
  • @PaulAbbott I'm sure that would be a perfectly good way to do it, but I was curious as to the syntax (or escape sequence) I needed to use in the problem above. Commented Sep 22, 2017 at 22:15
  • Works fine for me in both MVC4 and MVC5 Commented Sep 23, 2017 at 4:39
  • It works in ASP.NET Core MVC too. Commented Sep 23, 2017 at 7:19

3 Answers 3

1

You can use Html.Raw.

string lineTemplate = "<h{0}>{1}</h{0}>";
for (int tagCounter = 1; tagCounter < 7; tagCounter++)
{
    @Html.Raw(string.Format(lineTemplate, tagCounter, "Header "+ tagCounter));
}
Sign up to request clarification or add additional context in comments.

Comments

0

i am not sure which Razor version you are using

but i tested your code in my MVC4, it works perfectly

it will render <h1>something</h1>

Comments

0

@Html.Raw($"<{tag}>some title here</{tag}>")

Comments

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.