ASP.NET MVC Dynamic Forms

我的未来我决定 提交于 2019-11-27 09:35:34

问题


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.


回答1:


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.)




回答2:


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.




回答3:


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

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



回答4:


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
    }
);



回答5:


Try this http://mvcdynamicforms.codeplex.com/releases/view/43320 it should be helpful



来源:https://stackoverflow.com/questions/17229514/asp-net-mvc-dynamic-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!