I've decided upon the HtmlHelper rather than a partial view for this functionality.
Does anyone have an example that might accept, say, a collection of Author objects and output a comma-se开发者_高级运维parated string (MvcHtmlString?) of links to their books?
Are you looking for this.
public static class ListHelperExtension
{
public static string ToCommaSeperatedAnchorTags(this List<Author> Authorlst)
{
var sb = new StringBuilder();
foreach (var author in Authorlst)
{
foreach (string bookName in author.Books)
{
//you can also use TagBuilder
sb.Append("<a href='#'>");
sb.Append(bookName);
sb.Append("</a>");
}
}
return sb.ToString();
}
}
call this using
List<Author> lst = new List<Author>{
new Author {Name = "J k Rowling",Books = new List<string> { "Harry Potter1", "Harry Potter2"}},
new Author {Name = "John Rogers",Books = new List<string> { "Transformers1", "Transformers2"}}
};
string str = lst.ToCommaSeperatedAnchorTags();
If you want to make it as HtmlHelper to use it in Views you can write it as
public static class HtmlHelpers
{
public static MvcHtmlString ToCommaSeperatedAnchorTags(this HtmlHelper helper, List<Author> Authorlst)
{
var sb = new StringBuilder();
foreach (var author in Authorlst)
{
foreach (string bookName in author.Books)
{
sb.Append("<a href='#'>");
sb.Append(bookName);
sb.Append("</a>");
}
}
return new MvcHtmlString(sb.ToString());
}
}
and in the view you can add it as
@Html.ToCommaSeperatedAnchorTags(Model.lst)
Old question, but I was here as I needed a similar solution.
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)
You could use a display helper, but that would not be very reusable (separate helper for each property).
My first attempt ended with encoded output, so came up with this helper (add it directly to the cshtml) :
@helper CommaSeparatedHtmlStringList(IEnumerable<MvcHtmlString> list)
{
@Html.Raw(list.First())
foreach (var item in list.Skip(1))
{
@Html.Raw(", ")
@Html.Raw(item)
}
}
use with:
@CommaSeparatedHtmlStringList(books.Select(book=>Html.ActionLink(book.Title, "Action")))
I then started to convert to an html helper, so you could @Html.CommaSeparate(books.Selected...
) then realised you just need the @Html.Raw part to output HtmlStrings / MvcHtmlStrings, ie:
@Html.Raw(string.Join(", ", books.Select(book=>html.ActionLink...
If you still prefer a code behind helper:
public static MvcHtmlString CommaSeparated(this HtmlHelper helper, IEnumerable<MvcHtmlString> list)
{
return new MvcHtmlString(string.Join(", ", list));
}
use with
@Html.CommaSeparated(books.Select(book=>html.ActionLink(book.Title, "Action"))))
精彩评论