Search code examples
asp.net-mvcviewbagactionlink

Enable/Disable Html.ActionLink based on a ViewBag value


I have more ActionLinks on a view, MVC project I need to enable/disable these buttons based on a ViewBag value.

I have added this code in the view

@{ 
   if (ViewBag.ModifyOS)
   {
      @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success disabled" })
    }
     else
     {
       @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" })
      }
}

This way it is working correct, but I would like a more elegant way to achieve this. I have tried this way:

@{
   string Disabled = "";
   if (ViewBag.ModifyOS)
   {
    Disabled = "disable";
   }   
  }

and I have set this Disabled to ActionLink

 @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" , disabled = "@Disabled" })

I have tried this way:

@Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" , disabled = "@(ViewBag.ModifyOS)" })

But in both cases the button is always disabled.


Solution

  • Looks like you can handle disabling by adding disable class. Why not go with it?

    string cssClass = "btn btn-success";
    if (ViewBag.ModifyOS)
    {
        cssClass += " disabled";
    }
    
    @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = @cssClass })