Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.60/5 (3 votes)
Hi Programmers,

I'm looking for your advice on the best way to do about creating a form that is dynamic at runtime using ASP.NET MVC.

Like, I have a form for entering a company's address and then user is able to enter more contacts associated with that company. Here a button will be there for Adding Contact, and when it is pressed then a new part of the form, with the contact details, is loaded dynamically using jQuery.

If the button is pressed again, then a new part of the form is loaded in again so that means there are now two contacts that can be added from the form.

I want to add these part (More Contacts) with jQuery dynamically to my View.

Now when the form is submitted then I want to make sure that the forms data (including the dynamic area of the form) are binded to the Model properly using Model binding technique. How to do it?

Hope this makes sense,

Thank You!

What I have tried:

I have tried Model Binding but the dynamic part data is not binding.
Posted
Updated 4-Dec-18 6:59am

 
Share this answer
 
Comments
love goldsmith 4-Dec-18 12:39pm    
No, this is general model binding thing, I was looking for Model Binding in dynamically generated controls.
F-ES Sitecore 4-Dec-18 16:43pm    
If you're not even going to look at the examples you're given then there's not much point helping.
love goldsmith 5-Dec-18 11:54am    
I want dynamic model bindings, you have not read my question properly.
F-ES Sitecore 5-Dec-18 19:39pm    
You're going to have to update your question to explain why you mean by "dynamic model bindings" then, as it's obviously not what the rest of us understand it to mean.
This is how to create dynamic forms and send the values to the controller using Model Binding technique

You have a Contact.cs Model:

JavaScript
public class Contact
{
    public int StreetNo { get; set; }

    [Required]
    public string Address { get; set; }

    [Required]
    public int Telephone { get; set; }
}


Next, create an action method on the controller that has the parameter of IList type:

JavaScript
[HttpPost]
public IActionResult Index(IList contactList)
{
    if (ModelState.IsValid)
    {

    }
    return View();
}


Next, in your 'View', create a 'html table and a button' to Add Rows in the table:

JavaScript
<button id="AddButton">Add New Contact</button>
    <form method="post">
        <table>
            <thead>
                <tr>
                    <td>Street No</td>
                    <td>Address</td>
                    <td>Telephone No</td>
                    <td></td>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <button>Submit</button>
    </form>
    <input type="hidden" id="totalContacts" value="0" />


I also have an hidden input control that will keep track on the number of rows added to the table.

Now add the following jQuery code to the View that will do the rows addition and rows subtraction.

JavaScript
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script>
    $(document).ready(function () {
        $("#AddButton").click(function () {
            tc = parseInt($("#totalContacts").val());
            tc = tc + 1;
            $("#totalContacts").val(tc)

            $("tbody").append('<input type="text" name="[' + (tc - 1) + '].StreetNo" /><input type="text" name="[' + (tc - 1) + '].Address" /><input type="text" name="[' + (tc - 1) + '].Telephone" />Remove')
        });

        $("tbody").on("click", "span", function () {
            tc = parseInt($("#totalContacts").val());
            tc = tc - 1;
            $("#totalContacts").val(tc)

            $(this).parents("tr").remove();
        });
    });
</script>


Explanation: On the AddButton click event, a new row is added to the table from the below code:

$("tbody").append('<input type="text" name="[' + (tc - 1) + '].StreetNo" /><input type="text" name="[' + (tc - 1) + '].Address" /><input
type="text" name="[' + (tc - 1) + '].Telephone" />Remove')


Variable 'tc' gives the total rows currently there in the table, and is used to create the names of the elements (which is the most important part). Remember the names have to be create by adding [0]., [1]., [2]., etc before there names. This will help you to apply Model Binding technique in this scenario.

Take for example:

If there are 1 row then:

JavaScript
<input type="text" name="[0].StreetNo">
<input type="text" name="[0].Address">
<input type="text" name="[0].Telephone">


If there are 2 rows then:

JavaScript
<input type="text" name="[0].StreetNo">
<input type="text" name="[0].Address">
<input type="text" name="[0].Telephone">

<input type="text" name="[1].StreetNo">
<input type="text" name="[1].Address">
<input type="text" name="[1].Telephone">


I have a span element on the last td of each row of the table. Since it is dynamically generated so I used the jQuery On method to apply it's click event. Inside the span's click event, I am simply removing the row (in which it lies) by the .remove() method. Also I am updating the rows counter in the hidden input control.

JavaScript
$("tbody").on("click", "span", function () {
    tc = parseInt($("#totalContacts").val());
    tc = tc - 1;
    $("#totalContacts").val(tc)

    $(this).parents("tr").remove();
});


You can run the code, click the button on the form and you will get all values in the controller using "Model Binding".
 
Share this answer
 
Comments
love goldsmith 5-Dec-18 11:53am    
Thank you for this perfect solution. I have implemented it in my website. It worked perfectly.
Yogi S. 13-Dec-18 12:06pm    
my pleasure.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900