CheckBoxFor(t => t.boolValue, new { disabled="disabled" }) method to render a checkbox, in disabled mode.
The method renders a hidden field as well.
My question is why does this hidden field has a false value for disabled check box? I believe the purpose of the hidden field is to have some extra behavior over the default check box behavior
Is there a way to override default MVC functionality so that the value of this hidden field is based on the state of the checkbox even in disabled mode?
The hidden field is used to bind the checkbox value to a boolean property. The thing is that if a checkbox is not checked, nothing is sent to the server, so ASP.NET MVC uses this hidden field to send false and bind to the corresponding boolean field. You cannot modify this behavior other than writing a custom helper.
This being said, instead of using disabled="disabled"
use readonly="readonly"
on the checkbox. This way you will keep the same desired behavior that the user cannot modify its value but in addition to that its value will be sent to the server when the form is submitted:
@Html.CheckBoxFor(x => x.Something, new { @readonly = "readonly" })
UPDATE:
As pointed out in the comments section the readonly
attribute doesn't work with Google Chrome. Another possibility is to use yet another hidden field and disable the checkbox:
@Html.HiddenFor(x => x.Something)
@Html.CheckBoxFor(x => x.Something, new { disabled = "disabled" })
UPDATE 2:
Here's a full testcase with the additional hidden field.
Model:
public class MyViewModel
{
public bool Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel { Foo = true });
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content(model.Foo.ToString());
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.Foo)
@Html.CheckBoxFor(x => x.Foo, new { disabled = "disabled" })
<button type="submit">OK</button>
}
When the form is submitted the value of the Foo property is true
. I have tested with all major browsers (Chrome, FF, IE).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With