2

Trying to use a loop to build a series of table rows in Razor:

MvcHtmlString filesList = MvcHtmlString.Create("");
foreach (var file in orderRow.Files)
{
    fileList = fileList + "<tr><td  colspan='2'><a href='http://@file.Location/file.FileName' target='_blank'>@file.Description </a></td></tr>";
}
    @filesList
}

How to concatenate several MvcHtmlString instances leads me to think i'm on the right track with the above code but i'm working against Razor an am experiencing different mileage.

thx

Community
  • 1
  • 1
justSteve
  • 5,444
  • 19
  • 72
  • 137
  • You cannot use Razor syntax in a normal string. You need to manually concatenate **and escape** your objects. – SLaks Apr 10 '11 at 03:04
  • In this case you're building a big string and then immediately outputting it. If this is the real code, don't bother to build a string, just write the output. – Samuel Neff Apr 10 '11 at 03:06
  • Are you writing a normal method or are you in a Razor page? – SLaks Apr 10 '11 at 03:13

2 Answers2

2

Assuming you're writing a static method in a .cs file:

There's no point.
MvcHtmlString doesn't actually escape anything; it justs tells Razor / ASPX not to escape itself.

You should assemble your string normally using a StringBuilder, then return new HtmlString(builder.ToString()).

If you're in a Razor page, the whole thing is pointless; see the other answer.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

You're over-complicating the problem. You don't need to build a string at all for your situation, since you're just outputting the string directly after the loop. You can do this:

@foreach (var file in orderRow.Files) {
    <tr><td  colspan='2'><a href='http://@file.Location/file.FileName' target='_blank'>@file.Description </a></td></tr>
}

http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182