First of all thanks for your reply,Technically, web pages don't know when a user is leaving a page. Does changing focus to another tab count as leaving a page? Does refreshing the page count as leaving a page? Does closing a tab count as leaving a page? Does killing a browser using Task Manager count as leaving a page? Does turning off the computer count as leaving a page?
In most cases there is nothing you can do in just plain old Razor or the HTML generated by Razor. Some of the cases can be handled by using JavaScript, but then this now becomes a JavaScript question, rather than a Razor question.