Reputation: 3920
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!
Upvotes: 17
Views: 37152
Reputation: 61
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.
Upvotes: 6
Reputation: 1643
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);
}
Upvotes: 0
Reputation: 3659
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
Upvotes: 43