Dynamic Form in Asp.net MVC & jquery

As a user centered developer or designer, you want to make quick form typing experience especially for forms handles multiple similar values. The following example will show you how to perform inline insert using jquery and how to receive the posted values in controller.

dynamicForm

First

Setup the html structure. we have a html table with 2 column: Name and Telephone. Create a Add Row link that will call the javascript function.

</pre>
<form method="post"><a style="margin: 10px 0;" href="javascript:addRow();">Add Row</a>
<table id="formTable">
<thead>
<tr>
<th>Name</th>
<th>Telephone</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name" /></td>
<td><input type="text" name="telephone" /></td>
</tr>
</tbody>
</table>
 <input type="submit" value="Submit" /></form>
<pre>

Second

The Add Row function is a jquery function that clone the row of the table and append it to the end of table to create dynamic form effect.

<script type="text/javascript" src="../../Scripts/jquery-1.5.1.min.js"></script><script type="text/javascript">// <![CDATA[
        function addRow() {
            //copy the table row and clear the value of the input, then append the row to the end of the table
            $("#formTable tbody tr:first").clone().find("input").each(function () {
                $(this).val('');
            }).end().appendTo("#formTable");
        }
// ]]></script>

Third

Once the submit button clicked, the controller ActionResult will handle the post back values from FormCollection variable. When a form has multiple same name inputs, the value will become comma delimited value. Therefore we use the split function to parse the string into string array.

[HttpPost]
public ActionResult DynamicForm(FormCollection form)
{
    //the form values becomes comma delimited array when it come to server side
    string[] names = form["name"].Split(char.Parse(","));
    string[] telephones = form["telephone"].Split(char.Parse(","));

    //process values
    List contactList = new List();

    for (int i = 0; i < names.Length; i++ )
    {
        Contact c = new Contact();
        c.name = names[i];
        c.telephone = names[i];
        contactList.Add(c);
    }

    ViewData["rows"] = names.Length;

    return View();
}
}
Advertisement