Loading, please wait...

How to add control dynamically in Asp.net MVC using Javascript

Here I will explain How to add control dynamically in Asp.net MVC using JavaScript. We can also remove generated control on button click.

 Introduction:

Today in this article, I will explain How to add the control dynamically in Asp.net MVC using Javascript.

We are going to add and remove control dynamically using Javascript at the client side.

Follow these steps in order to implement “Add control dynamically in Asp.net MVC using Javascript in Asp.net MVC”

 

Step1: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty project > then click to ok

 

Step2: Create a controller.

Go to Solutions Explorer > right click on controller folder > Add Controller > Enter Controller name > Select template “empty MVC Controller   ” > Add.

Here I have created a controller “HomeController”

 

Step3: Add view for action in controller & design.

Right Click on Action Method > Add View > Enter View Name (Here I add Index) > Select View Engine (Razor) > Add.

 

 

Now write the following code and Javascript

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <script type="text/javascript">

 

        function GetDynamicTextbox(value) {

            return '<div><input type="text" name="txttest" style="width:200px;" /><input type="button" onclick="RemoveTextBox(this)" value="Remove" /></div>';

        }

        function AddTextBox() {

            var div = document.createElement('DIV');

            div.innerHTML = GetDynamicTextbox("");

            document.getElementById("divCont").appendChild(div);

        }

        function RemoveTextBox(div) {

            document.getElementById("divCont").removeChild(div.parentNode.parentNode);

        }

    </script>

</head>

<body>

    <div>

        <form method="post">

            <div id="divCont">

                <div><input type="text" name="txttest" style="width:200px;" /><input type="button" onclick="AddTextBox()" value="Add" /></div>

            </div><br/>

            <input type="submit" value="submit" />

        </form>

    </div>

</body>

</html>

 

 

 

In above code I have three Javascript functions, first one is “GetDynamicTextbox()” that is useful for creating the HTML of control, second function “AddTextBox()” for adding the control on button click and third function “RemoveTextBox()” for removing the control on button click

 

Step 4: Run Application.

We have done all steps, now It’s time to run the application

           

 

If you have any problem and face any difficulty then Share your experiences with us in the comments below!

Like this post? Don’t forget to share it!