ASP.NET MVC disables switches with Razor syntax

In an ASP.NET MVC application, I have two radio buttons. Depending on the logical value in the model, how to enable or disable the switches? (Switch values ​​are also part of the model)

My switches 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, otherwise, if model.Alive is false , I want to disable the radio buttons. Thanks!

+6
source share
3 answers

You can pass values ​​directly as htmlAttributes, for example:

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

If you need to check the model. Now you can 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

+22
source

My answer will be the same as ahmed's. The only problem is that the WantIt property will not be sent for submission, as it is ignored due to the disabled html attribute. The solution is to add HiddenFor above RadioButtonFors, for example:

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

Thus, all values ​​are visualized, and you return a boolean value to send.

+1
source

Or provide 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); } 
0
source

All Articles