Retrieve Values From Dynamically Appended MVC Partial View

Chee Hou
3 min readMar 4, 2021

Please have a look on Dynamically append view with MVC Partial View before continue reading this post.

Since a employee can have one or more than one skillset, at first I create a model for employee and skillset respectively.

EmployeeModel Class:

SkillSet Class:

The EmpId in Skillset class is serve as a foreign key to link employee and his/her skillsets.

In the client side, the code of getting employee basic info is very straight forward:

And the javascript code to get the one or multiple value for skillsets:

The document.querySelectorAll(“#id”) will get all the values from the html form element with that particular id. Since our html form element share the same id, so all those values will be stored into a array.

I have 3 html form elements (Technology, Expertise and Remark), so I need 3 arrays to store all of the values respectively.

Then, create a for loop to iterate all values inside the array. Since all array contains same length, it doesn’t matter which array you choose as a for loop iteration. (Of course we better consider to use ‘Technology’ array as a benchmark, because it is all what skillsets about and ‘Remark’ array can be blank )

Inside the for loop, create a variable name “skillSets” and push those values to the attributes of the skillSets object respectively.

lease note that the object name skillSets and all its attribute names (Technology, Expertise, Remark) must tally with our skillSets class, otherwise we cannot pass the object with value to the controller.

Next, we pass 2 objects with name “emp” and “skillSets” to our controller action named “CreateEmployee”.

C# code for CreateEmployee action:

Please make sure that the parameters name of CreateEmployee are also tally with the object name that pass via ajax.

Then we are done, we can add multiple skillset and click submit button, we now will able to retrieve multiple skillsets’ value.

I will stop here and not completing the process of storing the data into the database. You may want to do it with your own way.

Full source code can be download via GitHub

Thanks for reading.

--

--