Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC/Razor model binding collections when an element is missing

I've got a form that contains a variable length list of textboxes, rendered using a template similar to this..

 @Html.TextBox("items[" + itemIndex + "].Title", someValue)

So the final rendered HTML looks something like this...

<input id="items_0__Amount" type="text" value="Apple" name="items[0].Title">
<input id="items_1__Amount" type="text" value="Banana" name="items[1].Title">
<input id="items_2__Amount" type="text" value="Orange" name="items[2].Title">

On form submission this binds to my model just fine. However, I have a delete button that uses Javascript to remove one or more rows from the form. The problem is that, if you delete say the middle row, the HTML looks like this...

<input id="items_0__Amount" type="text" value="Apple" name="items[0].Title">
<input id="items_2__Amount" type="text" value="Orange" name="items[2].Title">

...and the indexes are no longer contiguous. This seems to confuse MVC and my model binder only gets passed the first row, not the last. Have I done something wrong, or does MVC just fail if indexes in lists aren't contiguous? What is the best solution to this problem?

I want to avoid using JS to re-index everything if possible.

Thanks!

like image 943
GoatInTheMachine Avatar asked Sep 13 '11 09:09

GoatInTheMachine


People also ask

What is @model in razor?

New @model directive Let's now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.

What is bind property in MVC?

Model binding allows you map request parameters to actions. This means action methods will have one or more parameters and those parameters will receive their values from the model binding framework.

Does MVC use razor?

Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC. Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.


1 Answers

Phil Haack blogged about something similar to this a while ago, although I'm not sure if it is still relevant to MVC 3. The post includes a work-around for the non-sequential index problem -

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

like image 119
ipr101 Avatar answered Sep 17 '22 17:09

ipr101