This is the fifth part of a series of practical examples with Umbraco 7 and MVC.
In Umbraco, forms need a controller that handles when the form is displayed and when it is posted back by the user.
The only way to add a controller to our project is from Visual Studio. Go to the Controllers folder and add a new empty Controller. Umbraco controllers need to inherit from SurfaceController.
Surface controllers do not render entire pages, Umbraco nodes do that. Instead, you use Surface controllers to Render Child Actions so your controller actions will often have the [ChildActionOnly] attribute.
Let’s create 2 actions public ActionResult ContactForm() and public ActionResult ContactForm(ContactModel model). The first action displays the form. You can use this action to get any necessary information from the user or pre-fill lists, etc.. The second action is the POST action used to process the information received.
The controller uses a ViewModel called ContactModel which should be created inside Models folder.
See a snippet code of the controller below.
Because it is a child action, Umbraco requires you to use RedirectToCurrentUmbracoPage or CurrentUmbracoPage as return action results. Therefore, the only way to send data back to the page is by using TempData. We send InfoMessage and ErrorMessage.
The controller is now ready to be used. Similarly to Search Results and Sitemaps, you need a Macro that is rendered inside a Text page.
Go to Developer > Partial View Macro Files > ‘…’ > Create > In Filename enter ContactForm > In Snippet choose Empty and leave create a Macro ticked. Add the following code to your Partial View Macro file:
@inherits Umbraco.Web.Macros.PartialViewMacroPage @Html.Action("ContactForm", "Contact")
This code snippet only Renders an action from the Controller.
Now you have a Macro that was also created. So that you can add it to a page, go to Developer > Right click on Macros > Reload nodes > and select ContactForm. Tick use in Rich text editors and save.
Now go to Content > Home > ‘…’ > Create > Text Page > Call it Contact Us. In the main body text editor insert a Macro and select ContactForm.