There has been a post on this topic before, but this will be more detailed and insightful inshaAllah.
Volume 2, Book 13, Number 750:
Narrated Jabir bin ‘Abdullah:
A person entered the mosque while the Prophet was delivering the Khutba on a Friday. The Prophet said to him, “Have you prayed?” The man replied in the negative. The Prophet said, “Get up and pray two Rakat.”
Volume 2, Book 13, Number 751:
A man entered the Mosque while the Prophet was delivering the Khutba. The Prophet said to him, “Have you prayed?” The man replied in the negative. The Prophet said, “Pray two Rakat.”
One of the etiquettes of visiting the Masjid, is the offering of two rak`aat glorifying Allaah upon arrival. These two rak`aat show honor and respect for the places of worship. These two rak`aat are known as “Tahiyyaht-ul-Masjid”, and display salutation for the masjid. The person entering the masjid performs them greeting the masjid; similar to the way a person greets somebody.
There is proof found in the hadeeth of Abu Qaatadah that this prayer is legislated. The Prophet (peace and blessings be upon him) said,
إِذَا دَخَلَ أَحَدُكُمُ الْمَسْجِدَ فَلاَ يَجْلِسْ حَتَّى يُصَلِّىَ رَكْعَتَيْنِ
“Whenever one of you enter the masjid he MUST not sit down until he prays two Rak’ah.” (Bukhari 433)
فَلْيَرْكَعْ رَكْعَتَيْنِ قَبْلَ أَنْ يَجْلِسَ
“Then he MUST pray two Rak’ah before he sits down”(Muslim 714)
In the Ahadith mentioned above (top), an instance is mentioned where Prophet (SAW) interrupts his khutba to ask a man if he had prayed tahiyyat-ul-masjid upon entering the masjid. And then he ordered him to get up and pray the two rak`aat. This is where the confusion starts. Is the Jumu`ah khutba more important or the tahiyyat-ul-masjid? Well, read point 4 here.
Is it mandatory, recommended, or just a voluntary deed? Does a person HAVE to perform these two rak`aat upon entering a masjid, or does he/she have an option? Well, there’s difference of opinion among scholars. Go through this link for details. In short, it is recommended and a “stressed Sunnah”.
So if it’s a stressed Sunnah, can we perform the two rak`aat even in the times when prayer is forbidden (example: after Fajr, after Asr)? Get your answer here.
Happy knowing + amal-ing. :D