0

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

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
manish
  • 31
  • 3
  • The thing is, I should only use tag helper, not `href`. Can you please suggest any other – manish Oct 10 '22 at 19:38
  • Does this answer your question? [asp.net conditionally disable a tag helper (textarea)](https://stackoverflow.com/questions/34866539/asp-net-conditionally-disable-a-tag-helper-textarea) – Poul Bak Oct 10 '22 at 21:18

2 Answers2

0

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

Dimitris Maragkos
  • 8,932
  • 2
  • 8
  • 26
0

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>                
}
Yiyi You
  • 16,875
  • 1
  • 10
  • 22