Asp.net mvc 5 Asp.net Mvc-如果禁用,则复选框在回发时始终未选中=true

Asp.net mvc 5 Asp.net Mvc-如果禁用,则复选框在回发时始终未选中=true,asp.net-mvc-5,Asp.net Mvc 5,我有一个复选框,在帖子上它总是显示false(未选中)状态-: 下面是简单的代码-: public ActionResult Index3() { var checkBoxTest = new CheckBoxTest() {Istrue = true}; return View(checkBoxTest); } [HttpPost] public ActionResult Inde

我有一个复选框,在帖子上它总是显示false(未选中)状态-:

下面是简单的代码-:

 public ActionResult Index3()
        {
            var checkBoxTest = new CheckBoxTest() {Istrue = true};
            return View(checkBoxTest);
        }
        [HttpPost]
        public ActionResult Index3(CheckBoxTest checkBoxTest)
        {

            return View(checkBoxTest);
        }
型号-:

public class CheckBoxTest
{
    public bool Istrue { get; set; }
}
视图-:

@using(Html.BeginForm())
{
    <div>
        Check Box Test:
        @Html.CheckBoxFor(model=>model.Istrue,new{@disabled="disabled"})    
    </div>
    <div>
        <input type="submit" value="Submit"/>
    </div>

}
@使用(Html.BeginForm())
{
复选框测试:
@CheckBoxFor(model=>model.Istrue,新的{@disabled=“disabled”})
}
每当我在服务器上发布它时,复选框总是显示未选中状态-

但是,如果我从属性中删除“new{@disabled=“disabled”}”,它就可以正常工作


我在互联网上看到的大多数人都使用了相同的技术来禁用复选框——在他们的情况下,它是如何工作的?或者可能是我犯了任何错误…

如果您真的想将值提交回服务器,在这种情况下,您可以添加如下隐藏变量:

 @Html.HiddenFor(model=>model.Istrue)   

Simon Svensson的评论是正确的,Ankit Vijay的评论提供了一个很好的解决方案

另一个解决方法是,如果您不介意未提交禁用复选框,则在
HttpPost ActionResult
中添加两行内容,如下所示:

[HttpPost]
public ActionResult Index3(CheckBoxTest checkBoxTest)
{
    ModelState.Remove("Istrue");
    checkBoxTest.Istrue = true;
    return View(checkBoxTest);
}
即使在发布期间不会选中该复选框,但在重新显示表单时也会选中该复选框


有关为什么需要
ModelState.Remove
行的详细说明,请参阅。

这只是html标准,禁用的输入元素不会提交。您真的需要禁用复选框吗?有一个只读复选框就够了吗?谢谢。很高兴知道禁用的输入元素不会被提交。要学的东西太多了。Readonly可能不适用于复选框?目前,我添加了新的{onclick=“return false”};)。非常感谢你提供的信息。