Embed if statement inside a "a href" tag in Razor

13,650

Solution 1

You're taking the wrong approach.

In the model class, add a getter like this:

string MarkButtonDisplay
{
    get
    {
        if(condition here)
            return "none";
        else
            return "block";
    }
}

And change the markup to:

<a id="spnMarkButton" href="javascript:void(0);" style="display: @Model.MarkButtonDisplay;" onclick="MarkStore(@storeRating.StoreId);">

Don't mix logic and markup.

Solution 2

Is there a specific reason it why it needs to be embedded in the tag?

@if(condition here)
{
    <a id="spnMarkButton" href="javascript:void(0);" style="display:none;" onclick="MarkStore(@storeRating.StoreId);">
}
else
{
    <a id="spnMarkButton" href="javascript:void(0);" style="display:block;" onclick="MarkStore(@storeRating.StoreId);">
}
Share:
13,650
RJ Uy
Author by

RJ Uy

Updated on June 26, 2022

Comments

  • RJ Uy
    RJ Uy almost 2 years

    How to embed if statement inside an "a href" tag.

    Like for example

    <a id="spnMarkButton" href="javascript:void(0);" @if(condition here) style="display:none;" else style="display:block;" onclick="MarkStore(@storeRating.StoreId);">
    

    But the code above is not working.