PiranhaCMS / piranha.core

Piranha CMS is the friendly editor-focused CMS for .NET that can be used both as an integrated CMS or as a headless API.
http://piranhacms.org
MIT License
2.01k stars 560 forks source link

Post a contact form with server validation retaining validation messages #1326

Closed polenter closed 4 years ago

polenter commented 4 years ago

Hello guys,

Supported by your Routing docs

and the source code of SinglePageWithComments

I have built my own ContactFormPage with the URL /contact, internally routed to the razor page /contactform.

In the model of my Razor Page ContactFormModel there is the following method:

public async Task<IActionResult> OnPost(Guid id)
{
    Data = await _loader.GetPageAsync<ContactFormPage>(id, HttpContext.User);

    // ... validate ModelState
    if (!ModelState.IsValid)
    {
        return Page();
    }

    // ...handle the request

    // ...show the message to the user
    SuccessMessage = "Thanks for your message...";
    return Redirect(_applicationService.Url(Data.Permalink));
}

If the ModelState is not valid, the return Page(); is called and the request will be redirected to /ContactForm, including all validation messages - almost as expected.

However I'd like to redirect the request to /contact, since this is the requested URL, configured in the manager, not to /ContactForm.

If I replace return Page() with return Redirect(_applicationService.Url(Data.Permalink)), the request goes to /contact. Unfortunately all validation messages are lost since the page is reloaded.

How should I redirect invalid POST request to /contact and retain the validation messages?

Piranha CMS is a great product with superb integration with Asp.Net Core and the easiest one concerning backend extensibility. Keep your great job and keep your product simple!

polenter commented 4 years ago

During refactoring I have solved the problem myself,

The issue concerns only the case, when a POST request is made to a handler, e.g.

contactform.cshtml

<form method="post" asp-page-handler="ContactForm">

contactform.cshtml.cs

public async Task<IActionResult> OnPostContactForm(Guid id) { }

URL

/contactform?handler=ContactForm

If the POST request is made to the backend, without a handler, the url in the address line, after the server validation is the same as formerly requested.

contactform.cshtml

<form method="post" >

contactform.cshtml.cs

public async Task<IActionResult> OnPost(Guid id) { }

URL

/contact
polenter commented 4 years ago

The problem is solved as long as the POST request does not concern a razor page handler, e.g. <form method="post"> instead of <form method="post" asp-page-handler="ContactForm">.