This blog post travels through a sample code to create HTML dynamic controls bound with model properties using jQuery and MVC’s HTML helper classes.
The below snapshots are written to implement the logic to create dynamic text boxes on button click event and also populate the available values in the respective Dynamic text boxes. Note that this also carry the logic for displaying the text boxes with values in database while the document is ready and add text box work for the consecutive button clicks till the text box number reaches 10.
Please find the descriptions below the snapshots.
The above div, “TextBoxesGroup” will be appended with the dynamic text boxes with the model values bound and add Dynamic text boxes during the button click event.
The above snapshot consists of the hidden div hard-coded with the div with the controls to be displayed on the button click. The div, “TextBoxDyn” will get appended to the div where we need the dynamic control is to be displayed and the div, “DynDate” will be helpful to check if the model holds any value respective to your textbox. Note that the model consists of the properties already that are assigned to the controls.
The steps followed in the above jQuery code are as follows:
1) “$(document).ready” ensures whether all the DOM objects got loaded
2) The variable “counter” is initiated to 1 and it is made to increment on every append or button click
3) The variable “divParentId” refers to the id of “TextBoxDyn” which will be concatenated with the counter for every iteration for append when the model already holds the value for the property respective to the controls.
4) The variable “divId” refers to the id of the “DynDate” which will be concatenated with the counter for every iteration for append when the model already holds the value for the property respective to the controls.
5) The for loop iterate to check if the property holds the value already till the model property is null.
6) After the iteration, the latest value of “i” is assigned to the counter, so that the button click event can happen only for 10 times and the append happens for the next div following the div with id appended last.
7) There will be an alert message after all the 10 controls got appended.
Now you can see your dynamic controls working perfectly with model binding.
Hope it helps. Happy coding!