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.
To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
The difference between them is that View Pages are Razor views that are used to provide the HTML representations (aka views) for services in much the same way View Pages work for MVC Controllers.
string.Format()
returns a string, which you're discarding.
You need to print that string to the page:
@string.Format(...)
Note that since this isn't a statement, there shouldn't be a ;
.
Also note that it would be better to use Razor itself:
<img src="@p.Path" width="100" alt="@p.AlternateText" />
I just simply do this to get around that problem:
@model UXLab.Areas.SectionArea.ViewModels.SectionViewModel
<section>
<header>@Model.Title</header>
<p>
@{var contentBuilder = new System.Text.StringBuilder(); }
@foreach (var link in Model.Links)
{
contentBuilder.append(Html.ActionLink(link.LinkText, link.Action,
link.Controller));
}
@Html.Raw(contentBuilder.ToString())
</p>
</section>
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 use Html.Raw
to display the raw Html, if you don't use Raw
then you'll not get quotes and things through to the page example:
1: @String.Format("\"Hello {0}\"", Model.Name)
2: @Html.Raw(String.Format("\"Hello {0}\"", Model.Name))
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With