I want to render images in a Razor view using string.Format
like this ...
foreach (var p in @Model.Photos)
{
string.Format("<img src='{0}' width='100' alt='{1}' />", p.Path,
p.AlternateText);
}
Something is clearly wrong here, because on rendering this page, I've got nothing inside this section.
It's true using
string.Format
is painful in Razor, but you do have anHtml.FormatValue
, here is how to use it:The method signature is:
I just simply do this to get around that problem:
In this example, I loop through some links I want to display to the page which are stored in a
ViewModel
.In order to display the Links on the page, I loop through them all appending them to a
StringBuilder
, then useHtml.Raw
to display the raw Html, if you don't useRaw
then you'll not get quotes and things through to the page example:Line 1 will display
" Hello " Melman
Line 2 will display
"Hello Melman"
Just some stuff I have found out when playing with outputting to the page. The basic idea is that, you build the page html up, then display it. So a store as you go method, once you finished manipulating the html output, you then display it using
@
outsite of any{}
string.Format()
returns a string, which you're discarding.You need to print that string to the page:
Note that since this isn't a statement, there shouldn't be a
;
.Also note that it would be better to use Razor itself:
I had the same problem and I've done it like this using Url.Content and string.Format: