In this tutorial, you will learn how to create a sign-up form block in Episerver CMS. When thinking about forms and blocks, data messaging becomes more complex. A block can usually be placed within any page type that contains a content area. This means a block will not have a static URL to post the form data back to the server, how do we solve this? Following the steps below, you will learn how to render a form control on a page, then post back to the page that calls it and trigger any ModelState errors, or, authenticates our visitor?

For this tutorial, I will use the block defined above. You are of course free to add whatever properties that you need. The main thing is you have a form block!

Redirection

As this log-in block can potentially be added to any page, after a user tries to log in, we need a way to send the users back to where they came from. To do this you will need to pass in the return Url when the form is submitted. After the Login() method is called, the controller will need to redirect the user to the page they made the original request from (in failure at least). The problem with performing a redirect is that you will lose the current page state. This can be annoying if you want to send error messages back to the user.

To overcome this snag, we could use TempData to pass data within the same request. TempDatais part of the MVC framework and it is an easy way to add custom data into a request that can be read later in the request pipeline from within a view. Normally, I'm not a big fan of using TempData as it seems hacky, however, the data only persists for the current page request so it is a viable option for our needs.

An alternative approach that I prefer, is to use the PRG Pattern for Data Modification for passing values between two controllers. The basic premise is that you use attributes on the action methods you want to share the Temp data between. This practice is a lot more robust as you do not need to manually store and retrieve information from Temp Data. Instead, you can use an ActionFilter to do get the data instead. The code to do this alternative approach is here:

ModelStateTempDataTransfer

ImportModelStateFromTempData

Now we have our action filters we can then decorate our actions as follows:

One thing to note about the code is how the re-direction process works. Within Episerver, as long as you set the node value with the correct page ID, you can use RedirectToAction. Even though there's CMS routing going on in the background the node property will ensure the request maps to the correct page controller. In this case, I set a hidden field in the form and use the CurrentPage property to set the value of node.


That outlines the process of how you can create a form that posts back to a controller in Episerver. Remember to add the AntiForgeryToken attribute to stop cross-site scripting attacks. A working example of this code can be downloaded from my GitHub account here. Happy Coding 🤘