CONTENTSTART
EXCLUDESTART EXCLUDEEND

Passing Parameters

There comes a point in almost every website that you have some form of a dynamic page that changes based on what information is passed to it.  Whether that’s as simple as the Search Page sending the search text to it, or something more complex like a shopping cart storing the current cart’s content and making it available from page to page.  Passing parameters around is a big part of your web sites and web systems.

This article is going to cover some different options available to you to pass and store values, how to set and retrieve these values in Kentico, and what are some pros and cons to each method, so you can pick the right one for your task.

Summary First

Because this article is a little more verbose, here is the TLDR (Too Long, Didn’t Read) version of different technologies and when to use each one:
  • POST: Use this in creating custom APIs that need to receive large sets of data (usually through XML / JSON)
  • Cookies / Web Storage: Use for user settings / preferences or sharing data between domains.
  • Session State: Use for large data or object storage for the user.
  • Query String: Use for passing parameters from “Search” type pages to “Result” type pages, or any page where the results need to be easily shareable via link.

POST

If you’re a developer, you’ve probably cut your teeth at some point on a simple HTML Form that posted to some dynamic script, such as a PHP contact us form or something similar. 

How it Works

When you make a request, you send with the request a Verb, which can be GET, POST, PUT, PATCH, and DELETE.  With these requests (usually POST), you can send data within the request, usually from a html form (although you can, using code, post other properties).  These properties are included in the POST request which are then available to the location you are sending them to.

How they are Set / Retrieved

Most HTML Forms can automatically POST input and select properties without any real modification.  If you have a custom tool that you want to post data to another page, or large data you want to post to another API, you can modify the Web Request you are generating and add POST values. An example can be found here on how to submit a POST requests.  You can also use Javascript / jQuery to send AJAX calls and post data.
The receiving page can then access the POST data through the Request.Form["TheVariable"].

What they are Good For

Since you can send larger chunks of data in a POST request, this technology is best used for larger API integrations.  Many APIs that need to receive many fields will ask that the data be POSTed to their API, usually in the form of an XML or JSON string.  They are also good for multi-field submissions (such as contact forms, although Kentico handles Forms better than any custom implementation).
So use this technology mainly for making APIs and receiving and processing large chunks of data.

Issues with POSTing

Data that is sent in the POST is often not accessible through javascript, so it’s not very usable for passing data that needs to be easily retrieved there.  It can also be a little tedious to get at the Form Data, and best left to server-side API scripts.
 

Cookies / Web Storage

Cookies act as a browser-based storage of properties that can be leveraged in many ways.

How they Work

Cookies operate through storing a Name: Value property on the browser, along with an indicator on what has access to the cookie (usually the current site domain but can be configured to be accessible across multiple domains), and an expiration date when the cookie is no longer valid.  These cookies are both sent to the server with page requests and are available through JavaScript.

 How they are Set / Retrieved

Cookies can be set in several different ways.  One way is when the server responds to a page request, it can include a “Set-Cookie” header that instructs the browser to store a cookie.  One common cookie that you’ll often see is your SessionID cookie.  You can set them using code to add your own Set-Cookie command to the header, and you can also add them with Javascript on the client side.

In terms of Kentico, here’s the ways you can work with them:

  1. On the Server Side, you can use the CMS.Helpers.CookieHelper class to help you get and set cookies.
  2. Using Macros, you can use the {% Cookies["CookieName"] |(user)tfayas|(hash)a9c6f43e7014a31a1d9f5717db9db77c932b9698291301560a865d0134911030%} to retrieve your cookies.

What they are Good For

Cookies have multiple benefits.  They can be set to be shared across domains, which makes using them to pass data between subdomains beneficial if they are set properly.  They don’t depend on a URL parameter which can be easily removed, and they can be set to persist which provides easy means of storing user data on the user’s browser without needing to store it on the database or create a user account for it.

They also are good for storing preferences to user interfaces, such as what language is selected, what region is selected, what font size they select, etc.

Issues with Cookies

There are a couple of issues with cookies that you should consider before using them.  First is the GDPR laws in Europe now restrict what you can use Cookies for and require user approval to leverage.  Kentico has a great information and webparts in Version 11 that allows you to easily request permission levels for your users to select, and then for you to leverage.

Another issue is that cookies are very much dependent on the user.  A user can clear their browser cookies at any time, or have cookies disabled entirely.  So, for things like passing a parameter between one page and another, they probably should not be used as this will not work for someone with cookies disabled.

Cookies are also limited to a Name:Value pairing, so it can be rather difficult to store large pieces of data in them.  Web Storage can handle that but isn’t as easy to access as Cookies.

The last issue is when Cookies are available after being set.  If you set your cookies through a server response, then the cookies are not available back to the server until the next request, so you can run into issues where you can’t see the cookie or use it until the page is refreshed one additional time.

Session State

Session is kind of like the Web Server’s version of cookies.  They operate in a similar fashion (Name/Object pairing).

How they Work

Depending on what type of Session State you use (InProc, SQL, or a 3rd party like Redis Cache) will alter where data is stored, but in general Sessions work by assigning a unique Session ID to a visitor (which is stored in their browser cookies), which is used (along with the parameter name) to store properties for that user.

How they are Set / Retrieved

Session values are Server Side, they must be set through code and cannot (to my knowledge at least) be set by the browser itself (although there is a work around in the Kentico Tricks section to set Session Properties using Javascript and an API).
You can set/get them through:
  1. HttpContext.Current.Session["MyVariableName"] = “Something”;
  2. Kentico’s CMS.Helpers.SessionHelper class.
  3. Using Macros, you can use {% Session[“MyVariableName”] |(user)tfayas|(hash)dec4b87e30534d2c0fc660c35bfc5ba8ea479b297e5f4fe266630aeef05b70b2%} to retrieve session values.

What are they good for?

Session values are great for storing larger or more complex data associated with a user.  Since it is readily set-able and readable in code you can leverage it heavily with storing properties that are widely used across your site.  And unlike cookies, once you set it it’s immediately available to be retrieved.

Sessions also can store objects, not just a string value, so you can store entire classes in session if needed.  Just be aware that objects are objects, meaning if you modify it then it will be modified for any other call, it doesn’t automatically clone.

Since session data is not permanently stored, it can also be used instead of Cookies to store user settings, if you can set those values server side instead of client side, and as long as you don’t need to modify them with JavaScript (again, see the Kentico Tricks section for a work around).

Issues with Session

Sessions have some pitfalls.  Firstly, the user can never see their session values.  This may be a good thing, but I’ve seen some people use Session values to pass parameters from a search screen to a results screen and it’s hard to change / modify the values passed because it must be done server side.

Sessions do have a similar limit as Cookies that if a user clears their cookies, they lose their Session ID and thus they lose their session all together.  Sessions of course are also temporary, so all the data will disappear when the user’s session expires.

Sessions also persist along with the user’s visits, so you should be careful using sessions to pass values from one thing to another if that value should only be for that one visit.  What I mean is, I wouldn’t store a Site Search string in session, because if I visit the search page again my Search Text will still be in session, resulting in the search page searching for my previous value again.

Query Strings

I won’t bore you with what Query Strings are, everyone has seen them and used them, parameters passed right in the url.

How they Work

Query strings are simple, they are a name-value pair that is added to the Url.  After the actual page address, there is a ? which indicates that the remaining items (until the # symbol) are query strings, and then it goes in the format of:

MyPage?MyParameter1=Hello&MyParameter2=World

How they are Set / Retrieved

Both Client and Server have access to these values, although to leverage them you often need to use some parsing functions.  Server doesn’t have the ability to “set” them unless it’s doing a redirect and adding them on there.  Client side can also set them.
In both cases though, you set them by redirecting the user to the url, with the Query string parameters included.
For Retrieving them:
  1. Server Side you can leverage CMS.Helpers.URLHelpers to get URL parameters
  2. Client Side you can check online for functions to retrieve url parameters (like here)
  3. Using Macros, you can use the {% QueryString.MyParameter |(user)tfayas|(hash)948d9d8a1b25c9a0d2f95da2ca91e3278c1cd2319d65ed137215f6058a02fb43%}, or {? MyParameter ?}
Note: You are limited when you use the {? ?} shortcut syntax in what you can all do, plus if you are using it to pass a value into a webpart property, and the Property name matches the Query String Name, it will interpret the statement as the Webpart’s Property, not the Query String.  So I recommend always using {% QueryString.MyParameter |(user)tfayas|(hash)948d9d8a1b25c9a0d2f95da2ca91e3278c1cd2319d65ed137215f6058a02fb43%}

What are they good for?

Query Strings are usually my go to method for passing values around pages.  They are excellent for passing values on a Search-Style page to a Results Page because it’s very easy to set values using JavaScript on things like a button’s click, or through a simple anchor tag’s href.

Another big benefit is it provides an address that you can replicate the results and share with others.  If you want someone to see the same set of dealers on a dealer locator, copying the entire URL that has your search parameters will allow them to immediately go to it.

It is also stateless, which means that it’s available immediately and not dependent on any page life cycle.  Lastly, it’s user agnostic (unlike cookies and sessions). 

Issues with Query Strings

There aren’t many issues with Query Strings, other than that they aren’t cookies/sessions that can persist.  They are limited in how much data they can pass through the parameter, and can’t pass objects, only values rendered as strings.

You do need to be careful with how you consume query string parameters, as people can try to maliciously add anything into a query string, and if you do not clean it up before you use it, you could end up opening security holes (especially when using things for query WHERE conditions).

Kentico Tricks

Some of the technologies we discussed have some limitations on Setting/Getting values between Client and Server Side.  Here’s some tricks to help you overcome these limitations!

Make Server Side Parameters Client Side

If you ever use Server Side Parameters (such as Session parameters) and you need them available Client site (in JavaScript), keep in mind that you can always use a webpart (such as Static Text or JavaScript), along with Macros to add either a global JavaScript variable that contains your parameter, or a hidden div that you can then access.

<script type=”text/javascript”>
var MyParameter = “{% Session[“MySessionVariable”] %}”;
</script>
<div style=”display:none;” id=”MyContent”>
{% Session[“MySessionVariable”] %}
</div>

This can also be done to pass Localized text to JavaScript (although you can also use macros in JavaScript as long as the JavaScript is rendered through Kentico’s GetResource page:

There have been cases where you really want to store something in a Session variable, but you need to set it through JavaScript client side.  In this case, what you want to do is make an API page that you can call using an AJAX Call, that then sets the Session value.Set Session Values Client Side.

$.getJSON("/API/Set-Session-Settings", { MyValue: “Set This” }, function(data) {  });

…
SessionHelper.SetValue("MySessionValue", URLHelper.GetUrlParameter(HttpContext.Current.Request.RawUrl, "MyValue"));
…

Conclusion

As with any technology, using the right one the right way can mean the difference between a flexible and well-designed application and a hard to use, hard to debug, hard to modify nightmare.  If you have your own tips or tricks on the area, send me a message and I’ll try to include them!
Comments
Blog post currently doesn't have any comments.
Is four > than nine? (true/false)
CONTENTEND