This is the second post in a series of using forms with Umbraco.  In today's tutorial, I'm going to cover how to create a "contact us" form.

Surface Controller

When working with MVC and Umbraco, you will need to work with controllers. Umbraco comes with two varieties, the RenderMvcController and the SurfaceController. When you want to use route hijacking to intercept requests from a published page to a specific document type. The surface controller, on the other hand, is used to interact with views, like when you want to post a form to a controller. Or you could write a child action to a view with a SurfaceController

Contact Us View Model

When we want to move data between the business layer and the presentation layer, we will need a view model to pass this data. For a contact form this view model may look like this:

The Surface Controller

The next step is to create a controller to render the contact us form and validate the form.

In the controller, we define two actions, an index action to render the view and a submit form action to process the  data. In the 'SubmitForm' action, we use the standard MVC validation things, like the ValidateAntiForgeryToken attribute and the IsValid property. I have omitted the code to process the form, you may want to send an email, or submit the data into Umbraco. After we do the form logic, we can use the TempData feature to pass information back to the view. The other way of doing this is adding an extra property on the view model.

The View

In the form the template property is set, a thank you for submitting this form message will be displayed.  If it hasn't, then a form will render based on the view models' properties.

A surface controller is not the same as a standard RenderMvcController. With RenderMvcController you can use route hijacking to get your pages called. When you use a surface controller you use it in the same way you would a partial. A surface controller with a form needs to be placed on a page, rather than the form in the whole page. In this case, you might render the form, using this snippet:

In order for everything to work, we use the Umbraco surface controller. The surface controller has methods and properties that hook into Umbraco to provide some of the routing requirements needed to post back to an Umbraco controller. The rest of the process is fairly simple, create a view model to pass information between the view and the controller. A view to render the HTML and a controller to process the submission.