0

I have written an MVC5 Html extension to determine whether a button I have on screen is disabled.

It is as below:

public static HtmlString IsButtonEnabled(this HtmlHelper html, bool buttonEnabled)
{
  return new HtmlString(buttonEnabled ? "" : "disabled=\"disabled\"");
}

My cshtml is as below:

<div class="col-sm-12">
  <a class="btn btn-default btn-block btn-metro" @Html.IsButtonEnabled(Model.IsMyButtonEnabled)
     onclick="location.href='@Url.Action("Index","MyController")'">
    <img src="~/images/myImage.png"> <span class="h2">My Button</span>
  </a>
</div>

The button is getting disabled as expected - however, due to using the onclick allows it to still be clicked. Is it possible to use my Html Extension with a Html.ActionLink?

I realise I could quite easily prevent the click using some js on the page - however, I would like to avoid that if possible.

UPDATE

The extension method is used by 10 different buttons on the screen. The generated markup for one of the buttons is as below:

<div class="col-sm-12">
      <a class="btn btn-default btn-block btn-metro" disabled="disabled" href="/MyController/Index">
        <img src="/myApp/images/myImage.png"> <span class="h2">My Button</span>
      </a>
    </div>

With Stephen comment below I change the on click to just be href - however, even though the button is disabled I can still click on it and the site navigates to the url specified

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116
  • 1
    Why are you using `onclick` instead of `href="@Url.Action("Index","MyController")"`?. And if you going to all the trouble of creating an extension method just to add the `disabled` attribute, why not generate all the html in it? –  Apr 19 '17 at 10:09
  • @StephenMuecke - the extension is used by 10 different button on screen and the markup differs for each button (should have specified that in the question) – Ctrl_Alt_Defeat Apr 19 '17 at 10:11
  • @StephenMuecke - updated the question - changed to href still allows me to click the button – Ctrl_Alt_Defeat Apr 19 '17 at 10:17
  • 2
    You cannot disabled links :) Refer also [How to disable HTML links](http://stackoverflow.com/questions/10276133/how-to-disable-html-links) –  Apr 19 '17 at 10:18
  • You learn something new everyday :) - updated to use button tag – Ctrl_Alt_Defeat Apr 19 '17 at 10:40

1 Answers1

2

You could change the "a" tag to "button" tag. The URL tag is not meant to be disabled.

<div class="col-sm-12">
   <button class="btn btn-default btn-block btn-metro" @Html.IsButtonEnabled(Model.IsMyButtonEnabled)
 onclick="location.href='@Url.Action("Index","MyController")'">
       <img src="~/images/myImage.png"> <span class="h2">My Button</span>
    </button>
</div>
Ionut Ungureanu
  • 1,020
  • 1
  • 13
  • 16