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.
- 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.
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