I’ve done this in the past, and i may have to do it again, but before i do, i want to throw it out there to see how people handle it.
Razor view:
<ul>
@Html.EditorFor(model => model.Questions)
</ul>
Which could produce:
<ul>
<li><input type="text" id="Questions_0__Title" name="Questions[0].Title" value="hi"/></li>
<li><input type="text" id="Questions_1__Title" name="Questions[1].Title" value="hi2"/></li>
<ul>
Pretty dead simple.
Now, i need to allow the user to add, edit or remove any of those “Questions”.
For Edit, it’s easy – no work req’d. But for add/delete, if i were to do it with jQuery, i would need to be smart about the way i generate the “id” and “name” attributes (e.g get a count of how many is there, add 1, etc), and for delete i would to “re-render” some elements (for example, if one was deleted, i would need to change the “id” and “name” attributes to be -1 for all following elements).
All of this is because it’s a form, and it needs to be model bound.
That to me is too hairy, so in the past, i have done an AJAX call to the server with whatever is on the form, then add/remove elements in the controller, and render a partial view. This way all the elements are “ready to be model bound”. I still need a little but of jQuery, but nowhere near as much.
Has anyone found a better way?
So i thought of a better solution, that requires not much JS at all.
Easy, why didn’t i think of this before.