Asp.net-mvc – ASP.NET MVC disable radio buttons with Razor syntax

asp.net-mvcrazor

In an ASP.NET MVC application, I have two radio buttons. Depending on a boolean value in the model, How do I enable or disable the radio buttons? (The values of the radio buttons are also part of the model)

My radio buttons currently look like this –

            @Html.RadioButtonFor(m => m.WantIt, "false")  
            @Html.RadioButtonFor(m => m.WantIt, "true")  

In the model, I have a property called model.Alive. If model.Alive is true I want to enable the radio buttons, else if model.Alive is false, I want to disable the radio buttons.
Thanks!

Best Answer

You could pass the values directly as htmlAttributes like so:

@Html.RadioButtonFor(m => m.WantIt, "false", new {disabled = "disabled"})  
@Html.RadioButtonFor(m => m.WantIt, "true", new {disabled = "disabled"})

If you need to check for model.Alive then you could do something like this:

@{
   var htmlAttributes = new Dictionary<string, object>();
   if (Model.Alive)
   {
      htmlAttributes.Add("disabled", "disabled");
   }
}

Test 1 @Html.RadioButton("Name", "value", false, htmlAttributes)
Test 2 @Html.RadioButton("Name", "value2", false, htmlAttributes)

Hope that helps