Bellash
Bellash

Reputation: 8204

If statement in razor with html parts

The following code seems bad arround | How to use the if statement in razor, with some htmls on the fly ?

   @foreach (var item in Model)
 {
    <li>
    @Html.DisplayFor(modelItem => item.Code)
    @Html.DisplayFor(modelItem => item.Title)
    @Html.DisplayFor(modelItem => item.Description)
    @Html.DisplayFor(modelItem => item.LastUpdate)
    @Html.DisplayFor(modelItem => item.Book2.Code)
    @Html.DisplayFor(modelItem => item.TypeOfBook.Label)
    @if(ViewBag.IsAdmin){            
        @Html.ActionLink("Edit", "Edit", new { id = item.BookID }) |
        @Html.ActionLink("Details", "Details", new { id = item.BookID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.BookID })
    }
    </li>
 }

Upvotes: 1

Views: 495

Answers (3)

Bellash
Bellash

Reputation: 21

use text tag

@if(ViewBag.IsAdmin){  
    <text>          
        @Html.ActionLink("Edit", "Edit", new { id = item.BookID }) |
        @Html.ActionLink("Details", "Details", new { id = item.BookID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.BookID })
    </text>
}

Upvotes: 0

Evgeniya Rudakovskaya
Evgeniya Rudakovskaya

Reputation: 319

You can wrap it with <text> tag:

@foreach (var item in Model)
 {
    <li>
    @Html.DisplayFor(modelItem => item.Code)
    @Html.DisplayFor(modelItem => item.Title)
    @Html.DisplayFor(modelItem => item.Description)
    @Html.DisplayFor(modelItem => item.LastUpdate)
    @Html.DisplayFor(modelItem => item.Book2.Code)
    @Html.DisplayFor(modelItem => item.TypeOfBook.Label)

    @if(ViewBag.IsAdmin){  
        <text>          
            @Html.ActionLink("Edit", "Edit", new { id = item.BookID }) |
            @Html.ActionLink("Details", "Details", new { id = item.BookID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.BookID })
        </text>
    }
    </li>
 }

Upvotes: 3

Zabavsky
Zabavsky

Reputation: 13640

You should indicate the beginning of the content with @:

 @foreach (var item in Model)
 {
    <li>
        @Html.DisplayFor(modelItem => item.Code)
        ....
        @if(ViewBag.IsAdmin)
        {
            @Html.ActionLink("Edit", "Edit", new { id = item.BookID }) @:|
            @Html.ActionLink("Details", "Details", new { id = item.BookID }) @:|
            @Html.ActionLink("Delete", "Delete", new { id = item.BookID })
        }
    </li>
 }

Upvotes: 1

Related Questions