Appending text to a MvcHtmlString in Razor
Trying to use a loop to build a series of table rows in Razor:
MvcHtmlString filesList = MvcHtmlS开发者_JAVA技巧tring.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
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.
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
精彩评论