Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC disable radio buttons with Razor syntax

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!

like image 520
A Bogus Avatar asked Feb 11 '13 15:02

A Bogus


People also ask

How to disable radio button in MVC?

The RadioButton can be configured to be initially disabled through its . Enable() setting.


1 Answers

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

like image 141
amhed Avatar answered Sep 19 '22 18:09

amhed