skip to Main Content

I’m trying to add comma(,) after "a" tag in foreach like this:

@foreach (var item in Model.Product.Categories)
{
    <a href="#" class="product-link product-cat-title">@item.Name</a>
    ,
}

but I’m getting error that says "} Expected". What should I do?

I’ve tested @string.join(", ", Model.Categories.Select(p => p.Name).ToArray()) but that will return string or text. I want Link!

It’s worth mentioning that I don’t want to add another tag Like <span> or <a>. I know they Work. And I’ll appreciate if someone could explain why it doesn’t work?

Thanks

2

Answers


  1. https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-8.0#explicit-delimited-transition

    Use this approach to render HTML that isn’t surrounded by an HTML tag. Without an HTML or Razor tag, a Razor runtime error occurs

    @foreach (var item in Model.Product.Categories)
    {
        <a href="#" class="product-link product-cat-title">@item.Name</a>
        <text >,</text>
    }
    
    Login or Signup to reply.
  2. You are getting the error because your syntax is incorrect. The comma is not presented in a valid manner.

    You can use the Html.Raw() Razor Helper to render the comma.

    @foreach (var item in Model.Product.Categories)
    {
        <a href="#" class="product-link product-cat-title">@item.Name</a>
        @Html.Raw(",");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search