skip to Main Content

I am using Razor pages in .net 5.0

I wanted to use anchor tag helper to generate href as shown below

<a asp-page="/Add" class="ml-4 d-lg-block" @* something *@)"

When add any c# code with tag helper it is giving a compile error
in this I have added @* something *@ but it is giving a compile error

and also If I use any condition to render a tag, It is throwing compile error

<a asp-page="/Edit" @(Model.Condition?"":"disabled")>

saying compile error : The taghelper ‘a’ must not have c# in the elemnts attribute declaration area

How can I use C# along with tag helpers to satisfy both of the above condtions

2

Answers


  1. This is the syntax you have to use to conditionally add the disabled attribute:

    <a asp-page="/Edit" disabled="@Model.Condition">...</a>
    

    When condition is true it will generate:

    <a href="..." disabled="disabled">...</a>
    

    and when condition is false it will generate:

    <a href="...">...</a>
    

    Keep in mind that anchor elements do not have a disabled attribute so you have to add additional CSS to disable them:

    a[disabled] {
        pointer-events: none;
    }
    

    This solution is explained in more detail here: https://stackoverflow.com/a/10276157/10839134

    Login or Signup to reply.
  2. disabled will not work for a tag,you can try to use a button,and add window.location.href in onclick:

    @if(Model.Condition==""){
        <button onclick="window.location.href='/Edit'" >...</button>
     }else
    {
        <button onclick="window.location.href='/Edit'" disabled">...</button>                
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search