Home > Enterprise >  Change text based on incoming value
Change text based on incoming value

Time:09-12

I have a page like this:

enter image description here

As you can see, there are True, and False values ​in the Urgent and Done sections. I want to change these posts.

I want it to write "Yes" if True and "No" if False. How I can do that?

My codes:

@using ToDoListApp.Models
@model List<TodoTable>

<table >
    <thead>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Task</th>
            <th scope="col">Urgent</th>
            <th scope="col">Done</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
            <tr>
                <th scope="row">@item.Id</th>
                <td>@item.Name</td>
                <td>@item.Urgent</td>
                <td>@item.Done</td>
            </tr>
        }
    </tbody>
</table>

CodePudding user response:

You can use an @if or for cleaner code you can use the ternary operator : ?.

<td>@(item.Urgent ? "Yes" : "No")</td>
<td>@(item.Done ? "Yes" : "No")</td>

CodePudding user response:

@Fadi Hania's answer is correct but I would like to suggest a different approach. You can add two calculated properties in your model class. This way if you need to show TodoTable in a different view you don't have to rewrite the logic.

public class TodoTable
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Urgent { get; set; }
    public bool Done { get; set; }

    public string UrgentDisplayValue => Urgent ? "Yes" : "No";
    public string DoneDisplayValue => Done ? "Yes" : "No";
}

Usage:

@foreach (var item in Model)
{
    <tr>
        <th scope="row">@item.Id</th>
        <td>@item.Name</td>
        <td>@item.UrgentDisplayValue</td>
        <td>@item.DoneDisplayValue</td>
    </tr>
}
  • Related