What is the most elegant way to use a partial view to display a comma-separated set of items?

I need to display a list of Person objects, for example, in comma-delimited format using Partial View in ASP.NET MVC. My problem is when rendering using the following code:

<% foreach (var person in Model) { %>
    <%= Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name)) %>,&nbsp;
<% } %>

I get the trailing comma after the last item. What is the most elegant / least stupid way to get this list of faces without the last comma?

My two options so far, in order, would be the following:

  • Use JavaScript to remove trailing comma on client side
  • Manually create a list using code, not markup, in a partial view

None of these options work for me - any ideas?

Thanks!

+3
4

:

<%=String.Join(
    ",",
    Model.Select(
        person=>
            Html
            .ActionLink<PersonController>(
                c => c.Edit(person.PersonID), 
                Html.Encode(person.Name)
            )
    )
    .ToArray()
)%>

()

+3
<% bool first = true;
   foreach (var person in Model) { 
     if (first) first = false; else Response.Write(","); %>
     <%= Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name)) %>
<% } %>
+2

I think, instead of using foreach, you have to go through a collection of people using a regular loop. This way you can detect the last iteration in the loop and avoid the last comma.

<% { int count=Model.Persons.Count();
     for (int i=0; i< count; i++) { %>
     <%= Html.ActionLink<PersonController>(c => c.Edit(Persons[i].PersonID), Html.Encode(Persons[i].Name)) %>
     <% if (i < count) { Response.Write(","); } 
   } %>
+1
source

Uses LINQ Aggregate to combine comma separated links without adding a trailing comma.

<%= Model.Select(person => Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name))
         .Aggregate((links, link) => links + ", " + link) %>
+1
source

Source: https://habr.com/ru/post/1711463/


All Articles