Matthew
Matthew

Reputation: 817

What's the purpose of enclosing razor strings with @("<foo>")?

I'm looking at someone else's HTML (in a .NET web application) and keep seeing code that looks like the following:

@("<foo>")

But it seems that this could simply be written as foo and achieve the same result. I'm assuming that this is razor syntax, but I don't understand the purpose of enclosing a string with @(" ").

Can anyone explain this? A clear answer has been surprisingly difficult to find using Google.

Thanks in advance!

Upvotes: 0

Views: 93

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

As a supplement to my comment above, here's an example of using it inside a for loop:

<div class="row">
@for (var i = 0; i < 9; i++)
{
    if (i != 0 && i % 3 == 0)
    {
        @("</div><div class='row'>")
    }

    <div class="col">@i</div>        
}
</div>

Which would roughly produce:

<div class="row">
    <div class="col">1</div>
    <div class="col">2</div>
    <div class="col">3</div>
</div>
<div class="row">
    <div class="col">4</div>
    <div class="col">5</div>
    <div class="col">6</div>
</div>
<div class="row">
    <div class="col">7</div>
    <div class="col">8</div>
    <div class="col">9</div>
</div>

Upvotes: 0

Carl
Carl

Reputation: 2295

One possible reason would be to allow closing a tag in multiple places e.g.

<div>
@(if foo == bar)
{
    //some content here
    </div>

}
else
{
    //some other content here
    </div>
}

Is not valid razor syntax where as

@Html.Raw("<div>")
@(if foo == bar)
{
    //some content here
    @Html.Raw("</div>")

}
else
{
    //some other content here
   @Html.Raw("</div>")
}

is valid.

Upvotes: 2

Related Questions