Tuesday, July 31, 2012

Dynamically Generate Form with jQuery and ASP.NET MVC

Hopefully it’s obvious that you probably won’t need to do this very often, but when it’s needed, it’s nice to have available. I thought I’d share this little helper to dynamically create a form, append it to body, and submit it...without AJAX.

First I'll show you how I'm converting my view model to a parameter list and a query string. Basically I've created an extension method that loops through properties and checks if it's an IEnumerable or not. If it is, then I loop through the values of that property. Otherwise, I just add the value. This method does not work with complex types. Typically view models are flat, so this works well most of the time.

The ToQueryString method just calls the ToParameterList, adds a ? to the front and then just selects what it needs from the parameter list.

The jQuery is pretty straight forward. I get the body, create a form with an action, loop through my param list creating a hidden input for each param, append the form to the body, and then submit it.


As always, if you know of a different and/or better way, please let me know.

If you don't need to post, you can just use a get, you could do something like this:


You can download a sample project at GitHub.

Shout it

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...