views:

143

answers:

3

I'm investigating ASP.NET MVC now and noticed that in ASP.NET MVC application, which is created by Visual Studio by default, links "Home" and "About" are staying active when the user is on "Home" and "About" page correspondingly, and after clicking on the current page link page is reloading itself.

What is the correct approach to disable link which points to the page, a user is already on?

How to do it without violating ASP.NET MVC approach?

+2  A: 

"Disabling" in terms of html is simply removing href tag. There cannot be any asp-net-mvc-magic here. you need to render your menu in a way that sets href to "" for current page.

For details, i'd recommend you to refer "Pro ASP.NET MVC Framework" book, chapter 5.

portland
Thanks for recommending very useful chapter from the book!
rem
+1  A: 

This is one of those situations where I think javascript fits the bill. For the small percentage of users that have javascript disabled, the links are simply active - no big deal, but for the majority of the users, a simple line of javascript on each page can disable the appropriate link by assigning an onclick handler that simply returns false.

Example:

<script type="text/javascript">
    $('#HomeLink').click(function(e) {
        e.preventDefault();
        return false;
    });
</script>

Control of the UI elements should be maintained in the view anyway, IMO.

Chris
+1  A: 

I would be inclined to argue that you should allow the link to remain active, even when on the selected page. This is so you can allow the user to explicitely refresh their view of the data you're displaying when they desire. The link should be highlighted to indicate that this is the currently selected page.

Otherwise if you don't want your user refreshing the page, you should remove the link (or <li /> or whatever) completely so that in the context of the application,the notion of refreshing the page doesn't exist, instead of indicating the currently selected page by a disabled link, use an explicit heading.

To achieve this result, you could use the following:

$("#menu").find('*[href]').each(function(index) {
    if ($(this).attr("href") == window.location.pathname) {
        $(this).parents("li").html("");
    }
});

If you need to keep the element visible, just remove the href:

$("#menu").find('*[href]').each(function(index) {
    if ($(this).attr("href") == window.location.pathname) {
        $(this).removeAttr("href");
    }
});

but I'd also modify the style so it doesn't just look like a broken link or something.

DaveDev