【问题标题】:Check boxes for an Array of objects对象数组的复选框
【发布时间】:2012-08-19 09:23:32
【问题描述】:

我有这个代码:

型号:

public bool[] ArrayOfBooleans = new bool[2];

查看

@using(Html.BeginForm())
{
    @:#1
    <input name="ArrayOfBooleans[0]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[0]" type="checkbox" value="false" />
    <br />
    @:#2
    <input name="ArrayOfBooleans[1]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[1]" type="checkbox" value="false" />
    <br />    
    <input type="submit" value="Submit"/>
}

当我发布此内容时,ArrayOfBooleans 中没有任何变化。甚至可以将复选框“附加”到数组元素吗?

注意:这是我的一个实际问题的简化形式。我必须使用集合和更复杂的对象。

【问题讨论】:

    标签: c# html asp.net-mvc-3 razor


    【解决方案1】:

    试试这个(对我有用):

    @using(Html.BeginForm())
    {
        @:#1
        <input name="ArrayOfBooleans[0]" type="checkbox" value="true" />
        <input name="ArrayOfBooleans[0]" type="hidden" value="false" />
        <br />
        @:#2
        <input name="ArrayOfBooleans[1]" type="checkbox" value="true" />
        <input name="ArrayOfBooleans[1]" type="hidden" value="false" />
        <br />    
        <input type="submit" value="Submit"/>
    }
    

    在模型中:

    public class A
    {
        public bool[] ArrayOfBooleans { get; set; }
    }
    

    在控制器中:

    [HttpPost]
    public ActionResult Index(A model)
    {
        return View();
    }
    

    【讨论】:

    • 这很难看,必须添加第二个同名输入才能从复选框中获取错误的布尔值,但它可以工作。隐藏输入必须在对应的复选框输入之后。分配给名称的第一个值会保留并且不会被覆盖。如果未选中该复选框,则它不会将“true”写入命名值,从而使命名值保持打开状态,以便隐藏输入向其写入 false。来自我的 +1。
    猜你喜欢
    • 2020-03-06
    • 2021-08-18
    • 2020-07-10
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多