Long considered the "Switzerland of Central America" for its peaceful and stable democracy, Costa Rica has seen a string of corruption scandals during the administration of outgoing president Laura Chinchilla, the country's first female president.
The scandals, combined with a sharp and growing income disparity between the haves and the have-nots, seriously hurt the official candidate.
With 76 per cent of the ballots counted, Solis -- a historian by training and candidate for the Citizen Acton Party (PAC) -- won 30.8 per cent of the vote, narrowly ahead of Johnny Araya from the ruling right-wing National Liberation Party (PLN), who had 29.6 per cent.
"We are going to win because we are a people that has decided to change!" a euphoric Solis told thousands of cheering supporters gathered at his campaign headquarters.
More From This Section
"A wave has risen like a great tsunami sweeping away traditional politics forever," he said.
Solis has never held political office and was largely unknown until months ago, though he has worked in several PLN administrations and once served as ambassador to Panama.
In early January, polls showed that Solis had only five-per cent support among voters. His party, formed to fight corruption and support of better income distribution, is just 13 years old.
Villalta had emerged as the leading anti-corruption, anti-establishment candidate until he faced a barrage of attacks from Araya, who portrayed him as a pro-gay marriage communist.