Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 651
Andrei Avatar asked Jun 21 '13 07:06

Andrei


2 Answers

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

[HttpPost]
public ActionResult ActionName(FormCollection collection)
{
    //collection["inputName"];
}
like image 93
Roman Bats Avatar answered Nov 09 '22 02:11

Roman Bats


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

like image 13
mcintyre321 Avatar answered Nov 09 '22 00:11

mcintyre321