Search code examples
html.netasp.net-mvcrazordynamic-forms

ASP.NET MVC Dynamic Forms


Can anyone suggest a good way to develope dynamic forms with ASP.NET MVC?

I have cascading dropdowns on the page (options in the dropdown depends on the value, selected in the previous dropdown).

All the values come from the database.

How can I implement such behavior using ASP.NET MVC?

Of course I'd like to receive all the values in the controller when I submit my form.


Solution

  • If you need to have some dynamic fields in your form, the best way for you would be to use some advanced javascript frameworks like Angular, Backbone, Knockout etc.

    If you need something more or less simple it is enough for you to use Knockout. For more advanced scenarios I would recommend Angular, but this is my personal preference.

    Here is a simple implementation of a dynamic form with Knockout:

    var model = {
        users: ko.observableArray(),
        addUser: function() {
            this.users.push({ name: ko.observable() });
        }
    };
    
    ko.applyBindings(model);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    <div data-bind="foreach: users">
        <input type="text" data-bind="value: name" /><br />
    </div>
    <button data-bind="click: addUser">Add user</button>
    
    <ul data-bind="foreach: users">
        <li data-bind="text: name"></li>
    </ul>

    Now, what about ASP.NET MVC?

    This is more tricky. Perhaps the best and the easiest way would be to use Ajax and post JSON to ASP.NET MVC Action. First of all, you'll need to get a JSON object from your form. With knockout it's very simple:

    var json = ko.toJSON(model);
    

    Now, when we know how to get JSON from form, next step is to send your data to an Action. jQuery is perfect for that:

    $.ajax({
        type: "POST", 
        url: "@Url.Action("AddUser")",
        data: ko.toJSON(model).users, // Serialize to JSON and take users array
        accept: 'application/json',
        success: function (data) { alert("Done!"); } // Your success callback
    });
    

    In our case we basically send an array of strings, thus ASP.NET MVC action should look like that:

    [HttpPost]
    public JsonResult AddUser(List<string> users)
    {
        return Json(data); // return something
    }
    

    This is definitely not the only one option of how to implement dynamic forms, but I think it's pretty effective. Hope it helps.