2010-08-25 28 views
10

我试图将元素的动态数组绑定到视图模型,其中可能缺少html中的索引在asp.net中绑定缺失元素的数组mvc

例如,与视图模型

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" /> 

,酒吧也只是空。我怎么能让模型绑定器忽略任何缺失的元素?即上述将绑定到:

FooViewModel 
{ 
    Bars 
    { 
      BarViewModel { Something = "a" }, 
      BarViewModel { Something = "b" }, 
      BarViewModel { Something = "c" } 
    } 
} 

回答

5

添加.Index作为第一个隐藏输入来处理乱序元素,正如Phil Haacked所解释的那样blog post:

<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" /> 
+3

非常接近,但接受的答案在这个网址有一个更完整的解决方案:http://stackoverflow.com/questions/8598214/mvc3-non-sequential-indices-and-defaultmodelbinder – Levitikon 2012-03-28 03:32:51

+0

@Levitikon - 在您的链接接受的解决方案是过度杀伤。你不需要为每个项目指定一个'.Index'。我已经多次使用上述方法,而不需要链接中描述的额外隐藏输入。另外,Phil Haack是ASP.NET MVC开发团队的成员,所以我非常确定他在他的博客中写的是要走的路。 – amurra 2012-03-28 14:16:00

+1

@amurra在Haack的文章中说他为每个领域使用一个单独的隐藏输入,所以看起来这是必要的。 – Mykroft 2015-05-01 15:00:47

-1

我不知道甚至工作!

考虑到这一点,ID都做一样的东西:

<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 

但我怀疑会以同样的方式绑定你描述

你可能会编写一个自定义模型绑定器,查找最大索引,制作一个大小列表,然后将这些元素放在正确的位置。

说了这么多,等别人张贴一个非常简单的属性,你可以把你的财产,使得它只是工作; d

0

MVC能够填充列表本身。

public ActionResult Index(FooViewModel model) 
{ 
    ... 

所以无论有无丢失MVC将为每个创建索引创建新List<BarViewModel>和 - [1],[3],[6]这将创造新的BarViewModel,并将其添加到列表。所以你会得到带有填充条的FooViewModel。

+0

是的,没有。看起来MVC在序列中存在间隙时停止构建阵列。 – Levitikon 2012-03-28 03:23:29

0

可能的解决方法可能是实例化视图模型和收集到正确的尺寸(假设它是已知的),然后用TryUpdateModel更新...类似:

[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