15
votes

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!

3
set the css to either enable disable or hide show the radio buttons. You could also not render the radio buttons at all. - Nate-Wilkins
Is there a standard "Razor/ASP.NET/MVC" way of doing this? - A Bogus
if (Model.Alive) { setcss enabled or @Html.RadioButonFor//Display radio buttons } Just check the model state if true set properties or don't create the radio buttons at all - Nate-Wilkins

3 Answers

41
votes

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

6
votes

My answer would be the same as ahmed's. The only problem is, that WantIt property will not be sent on submit as it is ignored due to disabled html attribute. The solution is to add a HiddenFor above the RadioButtonFors like this:

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

That way all the values are rendered and you get the boolean back on submit.

0
votes

Or provide an overload for RadioButtonFor?

public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, bool isDisabled, object htmlAttributes)
    {
        var linkAttributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        Dictionary<string, object> htmlAttributesDictionary = new Dictionary<string, object>();
        foreach (var a in linkAttributes)
        {
            if (a.Key.ToLower() != "disabled")
            {
                htmlAttributesDictionary.Add(a.Key, a.Value);
            }

        }

        if (isDisabled)
        {
            htmlAttributesDictionary.Add("disabled", "disabled");
        }

        return InputExtensions.RadioButtonFor<TModel, TProperty>(htmlHelper, expression, value, htmlAttributesDictionary);
    }