Dynamically append view with MVC Partial View

Chee Hou
2 min readFeb 28, 2021

--

I’m using mvc partial view to create dynamically append/delete view.

Supposing you are creating a employee register page and let user to keep adding their skillsets, which generally looks like the this:

Add View

The work around is very simple, first we create our partial view for skillset that going to keep append in our index page for every time the ‘Add Skill’ button is clicked.

This is the code for the partial view _SkillSet.cshtml, just a simple html markup

Then, include our partial view in our main index page.

Please take note that the partial view is under a div element with class name “SkillSetHeaderClass“, later we will need this to tell the computer keep append partial view under this div .

The button ‘Add Skill’ will trigger the append partial view function, so I create a action method “DisplayNewSkillSet” in controller, and it will be called for every time the button is being clicked. I’m using ajax to fire the event.

In the controller, the action DisplayNewSkillSet will return the view of the partial view _SkillSet.cshtml

As we can tell from the ajax function, once the event is fire successfully, it will return a view of _SkillSet.cshtml , and we will append it into the Div element with class name “.SkillSetHeaderClass”

Done.

Now you can have a dynamically generate view by using mvc partial view.

Delete View

You may also want to delete particular row of skillset, so I have added a ‘X’ button for the deletion. The javascript code for delete row is also very simple, just one line.

If you checkout my code, you may found out that my remove javascript code is $(this).parent().parent().remove(); , which have two parent(). This is because my delete button is located nested inside 2 Div , so, in order to delete all skillset element, I need to go up to two level by using .parent().parent() (you may need 3 level .parent().parent().parent() if you want to delete something on higher level and so on)

I will include on my next post regarding how we can capture the values from dynamically generate partial view ,so we can store it to the database.

Full source code can be download from GitHub

--

--

No responses yet