Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding arrays with missing elements in asp.net mvc

I am trying to bind a dynamic array of elements to a view model where there might be missing indexes in the html

e.g. with the view model

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

class BarViewModel
{
   public string Something { get; set; }
}

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

at the moment, bars will just be null. how could I get the model binder to ignore any missing elements? i.e. the above would bind to:

FooViewModel
{
     Bars
     {
            BarViewModel { Something = "a" },
            BarViewModel { Something = "b" },
            BarViewModel { Something = "c" }
     }
}
like image 790
James Hollingworth Avatar asked Aug 25 '10 10:08

James Hollingworth


1 Answers

Add the .Index as your first hidden input to deal with out of sequence elements as explained in this 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" />
like image 98
amurra Avatar answered Nov 09 '22 22:11

amurra