using string.Format in MVC Razor view page

2019-02-16 06:19发布

问题:

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.

回答1:

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" />  


回答2:

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 &#34; Hello &#34; 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 {}



回答3:

It's true using string.Format is painful in Razor, but you do have an Html.FormatValue, here is how to use it:

@Html.FormatValue("value", "format")

The method signature is:

FormatValue(object value, string format)


回答4:

I had the same problem and I've done it like this using Url.Content and string.Format:

<img src="@Url.Content(string.Format("~/Content/img/{0}", Resources.MyImage))" />