代码之家  ›  专栏  ›  技术社区  ›  James Hollingworth

中缺少元素的绑定数组asp.netmvc公司

  •  10
  • James Hollingworth  · 技术社区  · 15 年前

    我正在尝试将元素的动态数组绑定到一个视图模型,在该视图模型中,html中可能缺少索引

    e、 g.使用视图模型

    class FooViewModel
    {
       public List<BarViewModel> Bars { get; set; }
    }
    
    class BarViewModel
    {
       public string Something { get; set; }
    }
    

    还有html

    <input type="text" name="Bars[1].Something" value="a" />
    <input type="text" name="Bars[3].Something" value="b" />
    <input type="text" name="Bars[6].Something" value="c" />
    

    目前,条将是空的。如何让模型绑定器忽略任何缺少的元素?i、 e.上述规定将适用于:

    FooViewModel
    {
         Bars
         {
                BarViewModel { Something = "a" },
                BarViewModel { Something = "b" },
                BarViewModel { Something = "c" }
         }
    }
    
    4 回复  |  直到 15 年前
        1
  •  11
  •   amurra    14 年前

    添加 .Index blog 职位:

    <input type="text" name="Bars.Index" value="" />
    <input type="text" name="Bars[1].Something" value="a" />
    <input type="text" name="Bars[3].Something" value="b" />
    <input type="text" name="Bars[6].Something" value="c" />
    
        2
  •  0
  •   Stelloy    14 年前

        [HttpPost]
        public ActionResult SomePostBack(FormCollection form)
        {
            // you could either look in the formcollection to get this, or retrieve it from the users' settings etc.
            int collectionSize = 6; 
    
            FooViewModel bars = new FooViewModel();
            bars.Bars = new List<BarViewModel>(collectionSize);
            TryUpdateModel(bars, form.ToValueProvider());
    
            return View(bars);
        }H
    
        3
  •  0
  •   Echilon Mafarnakus    12 年前

    public ActionResult Index(FooViewModel model)
    {
       ...
    

    所以不管有什么遗漏,mvc都会创建新的 List<BarViewModel> BarViewModel 并将其添加到列表中。因此,您将获得带有填充条的FooViewModel。

        4
  •  -1
  •   Andrew Bullock    15 年前

    考虑到这一点,我做了如下工作:

    <input type="text" name="Bars.Something" value="a" />
    <input type="hidden" name="Bars.Something" value="" />
    <input type="text" name="Bars.Something" value="b" />
    <input type="hidden" name="Bars.Something" value="" />
    <input type="hidden" name="Bars.Something" value="" />
    <input type="text" name="Bars.Something" value="c" />
    

    a,,b,,,c
    

    但我怀疑这和你描述的一样

    您可能需要编写一个定制的模型绑定器来查找最大索引,生成一个该大小的列表,然后将元素放在正确的位置。