Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structuring complex web forms in ASP.NET MVC

Tags:

asp.net-mvc

What is a good approach in ASP.NET MVC for implementing a complex form where sections of the form are shown and hidden based on a user's inputs?

My background is in Webforms. I am frequently asked to build forms where a user selects an option from a dropdown list, triggering a handful of new fields to appear. A different selection might cause a different set of fields to appear.

In the past, I would handle this scenario via an UpdatePanel and a wrapper Panel around the fields that I want to show or hide. Validation is automatically disabled when the fields are hidden.

Going forward, I'd like to make use of MVC's attribute-based model validation, but is it possible to make the validation conditional on the values of other properties?

Also, how can I handle the toggling of blocks of form fields? I know how to do it manually in jQuery, but I'm hoping there's an approach that ties in with validation and server-side code.

I am liking MVC much better overall, but I haven't figured out how to handle this type of scenario very well. Likely I just need to shift my thinking to fit better with the MVC approach.

like image 515
Josh Earl Avatar asked Jun 07 '11 14:06

Josh Earl


1 Answers

Josh,

The first thing I's suggest is to make sure you use ViewModels for the pages that are mode complicated. A ViewModel is basically a Model you create for a specific View; for example, a ViewModel could be a composition of other classes.

As for dynamically changing the fields on your View, the best way is to use jQuery (or any other javascript library) to do it.

I also migrated from a web form environment and I know is difficult to change gears at the begining, but trust me, doing a simple jQuery even handler is much simpler than having to put in place a control panel and then the event handlers.

Not to mention that is much more efficient; update panels are after all making partial posts to the page, sometimes, with jQuery you don't even need to do that.

After a few projects with MVC, I actually now find it time consuming to go and do the Update Panels on web forms ;)

Hope this helps, -Covo

like image 127
covo Avatar answered Oct 14 '22 16:10

covo