Dynamically adding controls using jQuery asp.net

Download Sample Application : DemoDynamicallyAddingRowControls.rar (43.77 kb)

There are many ways to dynamically add some controls as per requirement and is achieved using server side, client side or mix of both approaches. The measure challenge of using server side approach is handling of automatic disappearance/elimination of dynamically-created-controls during PostBacks (that requires recreation of controls before/on Page_Load() in asp.net).

The simplest way is use of jQuery to create/add controls dynamically at client side. It saves server trips and so recreation of controls that was required to handle in each post back when we use server side technique. This jQuery mechanism can be weird into user controls and used in more decent manner.

In this post, we will use client side technique for dynamically creating controls. In this technique/approach, we have two simple way to get values of dynamically added control's at server side –

  1. Use $.ajax    -to post the control values to server
  2. Use of Request.Forms   -directly get values using name of controls

First one is very easy and we can pass values of our dynamically created controls in JSON/XML format to server side for further processing. In this blog post, we will use second method to get values of dynamically created controls.

Let’s create a template row that will be added dynamically. In this blog post example, our template row has two input boxes Name, and Email that will be added or remove dynamically as per requirement. Later, after putting n number of particulars (name & Email) into these dynamically created controls, we would submit it on server side.

var templateRow = "<tr>
         <td> <input name='Name' id='Name' type='text' />* </td>" +
         "<td> <input name='Email' id='Email' type='text' /> </td>" +
         "<td> <input id='btnAdd' type='button' value='+' /> <input id='btnRemove' type='button' value='-' /> </td>" +
         "</tr>"; 

Now, let's create a table in which we will append our templateRow dynamically - 

  <table id="controls" cellpadding="5" cellspacing="5" border="2">
            <tr>
                <td>
                    <input name='Name' id='Name' type='text' />*
                </td>
                <td>
                    <input name='Email' id='Email' type='text' />
                </td>
                <td>
                    <input id='btnAdd' type='button' value='+' /><input id='btnRemove' type='button'
                        value='-' />
                </td>
            </tr>
        </table>

Now, we are ready with our template and need to write some jQuery code that will dynamically append our templateRow and remove it as per requirement. 

 $(document).ready(function () {
            $("#btnAdd").live("click", function () {
                var templateRow = "<tr><td> <input name='Name' id='Name' type='text' />* </td>" +
                                      "<td> <input name='Email' id='Email' type='text' /> </td>" +
                                      "<td> <input id='btnAdd' type='button' value='+' /> <input id='btnRemove' type='button' value='-' /> </td>" +
                                   "</tr>";
                $('#controls').append(templateRow);
            });

            $("#btnRemove").live("click", function () {
                if ($("tr").length == 1) { alert("you can't delete last row"); }
                else { $(this).closest("tr").remove(); }
            });
        });

That's it! We have done all for client side. Let's see server side handling. as I said we will use Request.Form[] to get the value of dynamically created controls, so, C# code would be as -

        var names = Request.Form["Name"];
        if (names != null && names.Count() > 0)
        {
            var emails = Request.Form["Email"];
            List<MyData> lstMyData = new List<MyData>();

            names.Split(',').ToList().ForEach(p => { lstMyData.Add(new MyData() { Name = p }); });

            for (int i = 0; i < lstMyData.Count; i++)
            {
                lstMyData[i].Email = emails.Split(',')[i];
                Response.Write(lstMyData[i].Name + "   :  " + lstMyData[i].Email + "<br/>");
            }
        }

"MyData" is nothing but a class, and it is like -

    public class MyData
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

So, isn't it easy? This is the simplest example and still require a lot of tweaks so that it can be used for heavily. 

:)