Microsoft

A Form Routing Gotcha with ‘SitecoreRouteName’

The Problem
When utilizing the Html.BeginRouteForm() or Ajax.BeginRouteForm() in a view to render a form tag, it is common to define the route using ‘Sitecore.Mvc.Configuration.MvcSettings.SitecoreRouteName,’ which returns the path to the current page. So far, pretty easy stuff for setting up a form. In my particular case, I was POSTing an AJAX form and loading a second view onto the page.
So why was SitecoreRouteName setting my ‘action’ attribute to the website root…

<form action="/" method="post">

… when I was really looking for something like this?

<form action="/about/ask-question" method="post">
Microsoft - The Essential Guide to Microsoft Teams End-User Engagement
The Essential Guide to Microsoft Teams End-User Engagement

We take you through 10 best practices, considerations, and suggestions that can enrich your Microsoft Teams deployment and ensure both end-user adoption and engagement.

Get the Guide

In practice, I was getting null reference exceptions due to missing renderings that the form was expecting to be present on the page. Turns out I was just on the wrong page after the POST, which changed my page context.
The Cause
I struggled for a bit to understand why ‘SitecoreRouteName’ was returning the wrong path, but it did eventually dawn on me: I was recently using the Experience Editor, closed the editor, and began smoke testing on the same page, which was loading the page based on the ‘sc_item’ parameter (with the item ID GUID). In other words, I had this for a URL path:

website.com/?sc_mode=normal&sc_itemid=%7b1336EA6C-BA36-42F7-B9AB-5A078B9AB29B

… instead of this:

website.com/about/ask-question

So “SitecoreRouteName” was returning the right path all along (“/”) – I was just using the wrong URL, hence the improper routing. The lesson: be aware of URL routing when testing forms like this (or any other route-sensitive component).

About the Author

More from this Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to the Weekly Blog Digest:

Sign Up
Categories