Creating forms requires that you know your way around .NET Core MVC. So if you are familiar with adding view models, views and controllers you are ready to make your first form.
You can also use Umbraco forms. It lets you and/or your editors create and handle forms in the backoffice. This includes setting up validation, redirecting and storing and sending form data. Great UI, extendable and supported by Umbraco HQ.
In this example we'll create a basic contact form containing a name, email and message field.
Creating the view model
First, we're going to create the model for the contact form by adding a new class to the /Models folder. If the folder doesn't already exist, create it at the root of your website. Let's call it ContactFormViewModel.cs
Next, we add the view for the form to the /View/Partials folder. Because we've added the model and built the solution we can add it as a strongly typed view.
Finally, we're going to add the controller. Create a new empty class in the /Controllers folder (if the folder doesn't already exist, create it at the root of the website). Name it ContactFormController and make it inherit from SurfaceController. Inheriting from SurfaceController requires that you call its base constructor. If you are using an IDE: Integrated Development Environment, this can be done automatically.
usingMicrosoft.AspNetCore.Mvc;usingMyFirstForm.Models;usingUmbraco.Cms.Core.Cache;usingUmbraco.Cms.Core.Logging; usingUmbraco.Cms.Core.Routing;usingUmbraco.Cms.Core.Services;usingUmbraco.Cms.Core.Web;usingUmbraco.Cms.Infrastructure.Persistence;usingUmbraco.Cms.Web.Website.Controllers;namespaceMyFirstForm.Controllers;publicclassContactFormController:SurfaceController{publicContactFormController(IUmbracoContextAccessor umbracoContextAccessor,IUmbracoDatabaseFactory databaseFactory,ServiceContext services,AppCaches appCaches,IProfilingLogger profilingLogger,IPublishedUrlProvider publishedUrlProvider) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) {} [HttpPost]publicIActionResultSubmit(ContactFormViewModel model) {if (!ModelState.IsValid) {returnCurrentUmbracoPage(); } // Work with form data herereturnRedirectToCurrentUmbracoPage(); }}
If the model state is invalid, CurrentUmbracoPage() will send the user back to the form. If valid, you can work with the form data, for example, sending an email to site admin and then RedirectToCurrentUmbracoPage();.
Adding the form to a template
You can add the form to a template by rendering the partial view: