0

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?

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
A.F.N
  • 199
  • 2
  • 15
  • if it is /Home/Index#ToTop it wont but if its /Home/Index/#ToTop it will redirect – Sandip Bantawa Oct 01 '16 at 08:46
  • thanks for answer. but my problem is about other links. for example u are in this url "abc.com" and u click Home anchor with this href :"/Home/index#TopTop" at this point u will rediret to a same page "abc.com/Home/Index#ToTop" instead scrolling to top. – A.F.N Oct 01 '16 at 08:53

2 Answers2

0

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

Community
  • 1
  • 1
ArieKanarie
  • 944
  • 1
  • 15
  • 29
  • It isnt a ToTop(i used wrog name for that!sorry). but consider that as a "return to home" anchor. u want that scroll u in top of home page in home page. but redirect u to home if u are not really in home page? for this reason i didnt use only **** – A.F.N Oct 01 '16 at 09:03
  • See edit. If I understand you correctly the link must be different based on the current page you're on. – ArieKanarie Oct 01 '16 at 09:21
0

Anchor Tag Helper in ASP.NET Core

You can use "asp-fragment"

<a asp-controller="Speaker" asp-action="Evaluations" asp-fragment="SpeakerEvaluations">Speaker Evaluations</a>

The generated HTML is:

<a href="/Speaker/Evaluations#SpeakerEvaluations">Speaker Evaluations</a>