I have been searching for awhile to get the following done: adding items to a form after the form has been passed. I already managed to add the HTML for the new item to the form, but after posting it is not recognized. So, let’s make my problem a bit more clear:
I have an object, namely Project. In that project, I have a List, which contains name/email and a bool to check whether or not the member has been selected (through the use of a checkbox, ofcourse).
In the view, it generates a form where someone can enter the project details and select (pre-existing) members. There is a button as well, which can create new members. When the button is pushed, the project form is hidden and a new (PartialView/form) is presented. After filling out the required user details, it is sent through an AJAX request and a JSON object is returned.
The new user is added to the usertable, but the form does not seem to recognize the newly added member. I have checked the HTML that is generated by the helpers (@CheckBoxFor etc.) with the HTML that I inject into the table: it is the same.
I suspect that the form itself has to be reset in some way (rebinding?), but my search attempts have come up with nothing, execpt tutorials/stackoverflow questions that explain how to bind a model in a view, not the rebinding.
I apologize for the lack of code, I hope the explanation is enough.
I would recommend you reading the
Editing Variable Length Listarticle written by Steven Sanderson which illustrates a very nice approach to achieve that. The idea is that you should not use integers as indexes for the names of your input fields but Guids and use the.indexspecial hidden field to indicate the index of the current row to the model binder. This way no matter how many fields you dynamically add or remove from the form the model binder will always be able to successfully bind the collection property.In his article he also illustrated a nice
Html.BeginCollectionItemcustom HTML helper which hides this work.