Home > Blockchain >  How to use conditional JavaScript statement based on model value on a razor view?
How to use conditional JavaScript statement based on model value on a razor view?

Time:10-01

I am basically trying to hide the ACCEPT or REJECT buttons inside "buttons" div on my view based on the values of "d_status" which is either "ACCEPTED" or "REJECTED" or "PENDING" and these values are coming from the model, however I am quite to new to asp.net, here is my code:

<tbody>
    @foreach (var Data in Model)
    {
    <script>
    if (@Data.d_status == "ACCEPTED" || @Data.d_status == "REJECTED") {
    document.getElementById("buttons").style.display = 'none';}
    </script>
    <tr>
       <td>@Data.donor_ID</td>
       <td>@Data.donor_Name</td>
       <td>@Data.donor_condition</td>
       <td>@Data.donor_BG</td>
       <td>@Data.donor_date</td>
       <td>@Data.drequest_date</td>
       <td>@Data.d_status</td> //checks status
       <td>
        <div id="buttons"> //hide this div
         <a href="@Url.Action("AcceptDonorRequest","Admin", new {ID = Data.donor_ID })"
       class="btn btn-success btn-lg">ACCEPT</a>
         <a href="@Url.Action("RejectDonorRequest","Admin", new {ID = Data.donor_ID })"
       class="btn btn-danger btn-lg">REJECT</a>
        </div>
       </td>
     </tr>}
 </tbody>

Is there a better approach to this? Or how this can be fixed?

CodePudding user response:

You can do it like below

@if (Data.d_status == "ACCEPTED" || Data.d_status == "REJECTED")
{
    <div>

    </div>
}
else
{
    <div id="buttons">
        //hide this div
        <a href="@Url.Action("AcceptDonorRequest","Admin", new {ID = Data.donor_ID })"
            class="btn btn-success btn-lg">ACCEPT</a>
        <a href="@Url.Action("RejectDonorRequest","Admin", new {ID = Data.donor_ID })"
            class="btn btn-danger btn-lg">REJECT</a>
    </div>

}

CodePudding user response:

You can easily do this like this (Simplified the code a bit for readability):

@if (!(Data.d_status == "ACCEPTED" || Data.d_status == "REJECTED")) {
   <div> //hide this div
         <a class="btn btn-success btn-lg">ACCEPT</a>
         <a class="btn btn-danger btn-lg">REJECT</a>
   </div>
}

There is no need for javascript in this case. If the if condition is false everything inside it wont get rendered.

Heres a link to Microsoft Docs for this. Maybe it helps you to understand the Razor syntax more: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-5.0#conditionals-if-else-if-else-and-switch

  • Related