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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…