Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Old question, but I was here as I needed a similar solution. </p> <p>Assuming the question is actually: How to generate a comma separated list of HtmlString (MvcHtmlString) (as in the question title and assuming the author/books is just extra detail and not the crux of the issue)</p> <p>You <em>could</em> use a display helper, but that would not be very reusable (separate helper for each property). </p> <p>My first attempt ended with encoded output, so came up with this helper (add it directly to the cshtml) :</p> <pre><code>@helper CommaSeparatedHtmlStringList(IEnumerable&lt;MvcHtmlString&gt; list) { @Html.Raw(list.First()) foreach (var item in list.Skip(1)) { @Html.Raw(", ") @Html.Raw(item) } } </code></pre> <p>use with:</p> <pre><code>@CommaSeparatedHtmlStringList(books.Select(book=&gt;Html.ActionLink(book.Title, "Action"))) </code></pre> <p>I then started to convert to an html helper, so you could <code>@Html.CommaSeparate(books.Selected...</code>) then realised you just need the @Html.Raw part to output HtmlStrings / MvcHtmlStrings, ie:</p> <pre><code>@Html.Raw(string.Join(", ", books.Select(book=&gt;html.ActionLink... </code></pre> <p>If you still prefer a code behind helper:</p> <pre><code>public static MvcHtmlString CommaSeparated(this HtmlHelper helper, IEnumerable&lt;MvcHtmlString&gt; list) { return new MvcHtmlString(string.Join(", ", list)); } </code></pre> <p>use with</p> <pre><code>@Html.CommaSeparated(books.Select(book=&gt;html.ActionLink(book.Title, "Action")))) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload