【问题标题】:MVC checkboxes & FormCollectionMVC 复选框和 FormCollection
【发布时间】:2013-11-22 09:50:37
【问题描述】:

在一个批量编辑表单页面上,我显示了大约 50 个还具有一些布尔属性的对象。控制器从编辑页面接收包含所有值的 FormCollection。

    public void _EditAll(FormCollection c)
    {
        int i = 0;
        if (ModelState.IsValid)
        {
            var arrId = c.GetValues("channel.ID");
            var arrName = c.GetValues("channel.displayedName");
            var arrCheckbox = c.GetValues("channel.isActive");

            for (i = 0; i < arrId.Count(); i++)
            {
                Channel chan = db.Channels.Find(Convert.ToInt32(arrId[i]));
                chan.displayedName = arrName[i];
                chan.isActive = Convert.ToBoolean(arrCheckbox[i]);
                db.Entry(chan).State = EntityState.Modified;
            }
            db.SaveChanges();
        }
     }

现在,对于复选框,MVC 在表单上创建隐藏输入(否则“false”无法回发)。在控制器中,当接收到FormCollection时,这会导致我收到一个say数组的情况

  • 50 个 ID,
  • 50 个名字和..
  • 复选框有 71 个左右的值,

因为隐藏的复选框与可见的复选框名称相同。

有什么好的方法来处理这个问题并获得复选框的正确值?

【问题讨论】:

  • 您不想使用自己的视图模型来自动绑定复选框值吗?
  • 你认为这会处理复选框的事情吗?嗯,我试试看。
  • 无法正常工作(将我的实体列表及其正确状态从表单传递给控制器​​)​​。仅在仅发布一个实体的情况下才有效。
  • 请给我一个 cshtml 示例,其中包含一些您需要从中获取值的控件
  • 别打扰,谢谢你的帮助!您是否有一个示例页面的链接,可以同时编辑多个实体?我关注了youtube.com/watch?v=-lQr1zaVBEQ

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

我正在转换所有包含复选框值的数组:

"false" => "false",如果前面没有"true"

【讨论】:

    【解决方案2】:

    用于编辑具有布尔字段的实体数组的示例。

    实体:

    public class Entity
    {
        public int Id { get; set; }
        public bool State { get; set; }
    }
    

    控制器:

    public ActionResult Index()
    {
        Entity[] model = new Entity[]
            {
                new Entity() {Id = 1, State = true},
                new Entity() {Id = 2, State = false},
                new Entity() {Id = 3, State = true}
            };
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Index(Entity[] entities)
    {
        // here you can see populated model
        throw new NotImplementedException();
    }
    

    查看:

    @model Entity[]
    @{
        using (Html.BeginForm())
        {
            for (int i = 0; i < Model.Count(); i++ )
            {
                @Html.Hidden("entities[" + i + "].Id", Model[i].Id)
                @Html.CheckBox("entities[" + i + "].State", Model[i].State)
            }
            <input type="submit"/>
        }
    }
    

    唯一棘手的是 html 元素命名。
    More info 关于绑定数组。

    【讨论】:

    • 非常感谢您的努力和链接,会再试一次!
    猜你喜欢
    • 2011-11-15
    • 2010-12-15
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2011-04-19
    相关资源
    最近更新 更多