简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM