Friday, 23 December 2016

How to add controls dynamically in asp.net mvc using javascript



Video Tutorial:

Download Full Source Code:

Download here



Introduction:
 Here I will explain how to add controls dynamically in   Asp.net MVC using JavaScript and you can save that data in your database table.
Description:
So now we start.
Step1: In first step we write fallowing html in Index page
<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>
Step2:  Write fallowing JavaScript code in Index page
<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>
Step3:  Add fallowing code HomeController.cs file

[HttpPost]
public ActionResult Index(FormCollection fc)
   {
            string test = fc["txttest"];
            return View();
   }

Output:  Run project and get fallowing Output:

 
Thanks..

No comments:

Post a Comment

Ads Inside Post