A.F.N A.F.N - 1 year ago 90
ASP.NET (C#) Question

What set an anchor tag href to scroll to a div in all URLs like "/" and "/Home" and "/Home/Index" without redirecting in MVC

I need to set HREF attribute of an anchor tag to work in all URLs like "/" and "/Home" and "/Home/Index" to scroll in top of a div.

the problem is if i set that to "/Home/Index#ToTop" and someone click on that anchor tag, he/she will redirect from "/" or "/Home" to "/Home/Index#ToTop" that is not very nice!

any idea?

Answer Source

If you just want to scroll to the top <a href="#"> will bring you back to the top of the page. If you want to scroll to an element that's somewhere on the page use <a href="#id-of-div"> so without the /Home/foo/bar stuff.

See also: What is href="#" and why is it used?

Edit based on comment
So you want the link to scroll to top of home page if you're still on the homepage without redirect, and you want the link to redirect you to home page and scroll to top of it, if you're not on the home page? I think you've to create a different link depending on the page you're on. So if user is yoursite.com/home, the link will be <a href="#id-of-div"> and if user is yoursite.com/foo/bar the link will be <a href="./Home/Index#id-of-div">

You can determine the current URL in the controller. Quick search on SO gives me:
How to get current page URL in MVC 3 In .NET MVC, is there an easy way to check if I'm on the home page?

It's been a while since I've worked with MVC, so I can only help with some old memories and quick searching

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download