Adding Multiple Nested Data in ASP.NET MVC Application
In one of the last articles we discussed how to populate hierarchical data using Model Binders in ASP.NET MVC Application. In this article we are dynamically add the items to the DOM tree which will result in adding new items to our C# model object.
The scenario is pretty simple! We have a page which allows the users to add a new category. Before adding a new category to the database the page also allow the user to add multiple products to the category. Users can add any number of products to the category object. Before implementing the View and the Controller let's take a look at the structure of the Model.
Category and Product Model:
The relationship between the Category and Product entities is one to many relationship. This means a single Category can have multiple Products. The implementation for both the classes is shown below:
As, you can see both the classes are very straight forward with minimal properties. Now lets see how the view is implemented.
The view consists of a single TextBox for adding the category name, add product button and a save category button. The implementation is shown below:
The following screenshot shows what the view will look like in the browser:
The purpose of the above code is to add a new TextBox to the page with a special name. The special name is created dynamically and it corresponds to the hierarchical structure of the object. The following screenshot shows the dynamic elements being added to the "products" DIV element.
The special names matches the structure of the model and hence it is populated by the default model binder. When you invoke the "Create" action you will notice that the "Products" collection inside the "Category" object is populated with the correct data as shown in the screenshot below:
In this article we learned how to add nested entities to our model using dynamically created HTML elements. You must make sure that the name of the element matches the correct hierarchy of the element. Although this method is not very straight forward but it can be utilized in some applications.