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.
You can use FormCollection as a parameter to receive all data that comes from the form:
[HttpPost]
public ActionResult ActionName(FormCollection collection)
{
//collection["inputName"];
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With