Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

asp.net mvc - Asp .net mvc 3 CheckBoxFor method outputs hidden field, that hidden field value is false when checkbox is disabled with selected true

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...