ASP.NET MVC Dynamic Forms

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 15:49:35

You can do this very easily using my FormFactory library.

By default it reflects against a view model to produce a PropertyVm[] array:

```

var vm = new MyFormViewModel
{
    OperatingSystem = "IOS",
    OperatingSystem_choices = new[]{"IOS", "Android",};
};
Html.PropertiesFor(vm).Render(Html);

```

but you can also create the properties programatically, so you could load settings from a database then create PropertyVm.

This is a snippet from a Linqpad script.

```

//import-package FormFactory
//import-package FormFactory.RazorGenerator


void Main()
{
    var properties = new[]{
        new PropertyVm(typeof(string), "username"){
            DisplayName = "Username",
            NotOptional = true,
        },
        new PropertyVm(typeof(string), "password"){
            DisplayName = "Password",
            NotOptional = true,
            GetCustomAttributes = () => new object[]{ new DataTypeAttribute(DataType.Password) }
        }
    };
    var html = FormFactory.RazorEngine.PropertyRenderExtension.Render(properties, new FormFactory.RazorEngine.RazorTemplateHtmlHelper());   

    Util.RawHtml(html.ToEncodedString()).Dump(); //Renders html for a username and password field.
}

```

Theres a demo site with examples of the various features you can set up (e.g. nested collections, autocomplete, datepickers etc.)

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.

You can use FormCollection as a parameter to receive all data that comes from the form:

[HttpPost]
public ActionResult ActionName(FormCollection collection)
{
    //collection["inputName"];
}
mipe34

I would create partial views for each option of the dropdown and additional fields. Than controller, that will return such parts of html according to dropdown value:

public class FormFieldsController : Controller
{
    public ActionResult Index(string dropDownOption)
    {
        if(dropDownOption == "Option1")
           return PartialView("PartialForOption1");
       etc.//
    }
}

Then just call it with jquery Ajax and append your current form with result of action, when the value of dropdown changes.

$.ajax("/FormFields/Index",
    {
        async: false,
        data: { dropDownOption: $('#dropDownId').value()},
        success: function(data) {
            if (callback == null) {
                $("#form").append(data);
            } else {
                callback(data);
            }
        },
        error: function() {
            alert('Error');
        },
        type: 'GET',
        timeout: 10000
    }
);
Soner
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!