You "can" mount the track directly onto the foam, but you must first consider where your track centerline will be and ensure you do NO carving there...or you must make provision for a substitute surface of some kind to support the tracks, be it a bridge, overpass, or some other surface. So, with a blank surface, unmarred, carefully plan out your track arrangement, draw a centerline, and then either place the track and cover it while you carve where you intend to, or stack layers to get higher terrain, or you can just leave an inch on either side of the centerline, do the carving and stacking for hills, and then add the track layer.
You can use an adhesive on the foam, such as PL300, which is safe for the foam, and lay a very thin smear of it under your tracks. The idea is to keep your rail elements fixed, but also to make it relatively easy to slide a blade under the rails, slice a bit, and pry them up to free them from the foam so that you can use the rails another time. Thick gobs of the caulk, which is what PL300 is, will make that process very difficult and messy.
In any case, you really ought to consider using a cork or foam, or thin vinyl rug underlay, for roadbed to elevate the tracks, unless you are using the snap tracks with the plastic roadbed, such as EZ-Track or UniTrack. The rails should be supported in ballast and therefore be elevated somewhat above the surrounding terrain and drainage to look right.