Search code examples
htmlasp.net-corerazor-pages

Replacing true or false in table value with an image in Razor Pages


Hi I am coding in Razor pages. I have a table where one of my values is boolean value where it shows either true or false in the table at the moment. I would like to switch these values with images in my wwwroot folder. The variable with a boolean value is the @tool.Borrowed.

My HTML Code

<table border ="1" class="table table-sortable">
    <thead>
        <tr>
            <td><b>Verktøy Nummer</b></td>
            <th>Modell</th>
            <td><b>RFID nummer</b></td>
            <th>Kategori</th>
            <th>Utlånt</th>
            <td><b>Siste ansvarlige person</b></td>
        </tr>
    </thead>
    <tbody>
        @foreach (var tool in Model.Tools) //Get the nessecary Tools from the tools Model from Tools.csgtml.cs
        {
        <tr>
            <td>@tool.ToolNumber</td>

            <td><a asp-page="/Tools/Details" asp-route-ID="@tool.ToolId">@tool.Model</a> </td>

            <td> @tool.ToolId </td>
            <td> @tool.Category</td>            
            <td> @tool.Borrowed</td>
            <td><a asp-page="/Employees/Details" asp-route-ID="@tool.EmployeeId">@tool.EmployeeName</a> </td>
        </tr>
        }
    </tbody>
</table>


Solution

  • If you want to add images depending on the value of @tool.Borrowed.You can use conditional operator.Here is a demo:

    wwwroot structure:

    enter image description here

    cshtml:

    <table border="1" class="table table-sortable">
        <thead>
            <tr>
                <td><b>Verktøy Nummer</b></td>
                <th>Modell</th>
                <td><b>RFID nummer</b></td>
                <th>Kategori</th>
                <th>Utlånt</th>
                <td><b>Siste ansvarlige person</b></td>
            </tr>
        </thead>
        <tbody>
            @foreach (var tool in Model.Tools) //Get the nessecary Tools from the tools Model from Tools.csgtml.cs
            {
            <tr>
                <td>@tool.ToolNumber</td>
    
                <td><a asp-page="/Tools/Details" asp-route-ID="@tool.ToolId">@tool.Model</a> </td>
    
                <td> @tool.ToolId </td>
                <td> @tool.Category</td>
                <td><img src="@(tool.Borrowed?"/imgs/true.jpg":"/imgs/false.jpg")" /></td>
                <td><a asp-page="/Employees/Details" asp-route-ID="@tool.EmployeeId">@tool.EmployeeName</a> </td>
            </tr>
            }
        </tbody>
    </table>
    

    cshtml.cs(I only test @tool.Borrowed):

     [BindProperty]
                public List<Tool> Tools { get; set; }
                public void OnGet()
                {
                    Tools = new List<Tool> { new Tool { Borrowed = true }, new Tool { Borrowed = false }, new Tool { Borrowed = false } };
                }
    

    result: enter image description here