views:

21

answers:

1

Hi,

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" }
     }
}
A: 

i didnt know even that worked!

bearing that in mind, id have done something like:

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

which would hopefully post

a,,b,,,c

but I suspect that will bind in the same way as you describe

Youre probably going to have write a custom model binder that looks for the max index, makes a list of that size then puts the elements in the correct place.

Saying all that, wait for someone else to post a really simple attribute you can put on your property that makes it just work ;D

Andrew Bullock