Shouldn't all the dwarves in the dwarven army that fought in the fifth blight become casteless?
I mean, their whole society shuns ever going to the surface, to the point that even taking a glimpse at the sky could make a dwarf casteless. So, shouldn't every single dwarf that went to the surface to fight the darkspawn and the archdemon in the fight at Denerim become casteless?
They were going to fight the Darkspawn, which is considered a sacred duty of all dwarves. If a dwarf were to join the Wardens, they would retain their caste. Even though these soldiers didn't join the Wardens, they were still fighting Darkspawn. And they were acting on orders from the King. If they went to the surface on the King's orders, then it doesn't count, and they keep their caste.
Don't forget that the dwarves specifically signed a treaty pledging support to the Grey Wardens during blights. If that entails making them casteless, then the treaties would generally not be honored.
Blights are the example in Thedas of exigent circumstances.