Eventually a component on a page is going to need to pull in some new information and you don't always want to reload the whole page. Making use of Ajax allows you to avoid a full reload but when you use Ajax with Sitecore there are a few important things to keep in mind:
- Make sure you set up your controller to function with the Ajax call. Are you sending back some data, the whole rendering, or are you just updating something internally? Be ready to handle whatever is coming into or out of the controller. Note that if the Ajax function is posting data you must add [HttpPost] before the controller method.
- Regardless of how you get to your controller - there won’t be Sitecore context! Your controller has no idea what the user was doing or where they were on your site when the Ajax call was made. You need to pass all the information in your model to the controller including the data item and anything else relevant for your controller to give context. One way to give context is to output a relevant ID (or the Sitecore Context ID) somewhere on the page. You can then grab the value via javascript to pass back to the model for when you lose context.
- Data can get complicated when passing back and forth between controller and JS - create a model which represents the data you’re working with to keep things clearer. The simplest way to do this is to use strings/integers etc for the fields you need to pass back and forth via JSON. Something like Quicktype.io ( https://app.quicktype.io/ ) can help you quickly generate C# models from your JSON (or other) data to use with the controller on the server side.
- Event binding can be lost if content is being reloaded via Ajax depending on how it was bound initially. If you have other javascript tied to any part of the component or page that’s being updated - either make sure that your javascript around those components is bound to something other than itself (such as the body tag), or that you run the js again once the call is complete. Otherwise, you’ll find the js runs once, and then isn’t firing since it was being bound to items that no longer exist.
For example, some jQuery to bind to body for a click event:
An example ajax call: - Don’t load your entire site to test a single controller, use Postman (or something similar) to test out your controller without needing to hit the page! This way, you can make sure your Ajax calls will work with the controller. https://www.getpostman.com/
This comment has been removed by a blog administrator.
ReplyDelete