Tepu
Tepu

Reputation: 1702

How to get MVC ActionLink Full Path in Jquery

I am trying to set the class on the selected menu anchor based on the URL. I have below actionlinks

@Html.ActionLink("Home","Index","Home" new {type="new task"},null)
@Html.ActionLink("Home","Index")

I need to get its fullpath in Jquery to change the selected link based on the url as given below

$("a").each(function () {
 if (location.indexOf($(this).prop('href')) != -1) {
                          $(this).addClass('mlnkactive').siblings().removeClass('mlnkactive');
                        $(this).parent().addClass('mlnkactive').siblings().removeClass('mlnkactive');
});

The problem is that when i get href of the links using $(this).prop('href') , both of the above Home links have the same href.So both of the Anchors are selected and I am unable to set the class on the selected Link based on URL.

Thanks,

Upvotes: 0

Views: 692

Answers (2)

Dawid Rutkowski
Dawid Rutkowski

Reputation: 2756

Maybe try to user normal with @Url.Action inside href attribute. For example:

<a href="@Url.Action("action_name", "controller", new { action_parametr_name = action_parameter_value})">Link 1</a>

Upvotes: 0

jgauffin
jgauffin

Reputation: 101150

Why don't you add a css class to the selected link server side (in the ActionLink)?

<div id="menulinks">
    @Html.ActionLink("Home","Index","Home" new {type="new task"}, new { @class = "mlnkactive" })
    @Html.ActionLink("Home","Index")
</div>

And then remove the class and add it to the new selected link client side? Like this:

$('#menulinks a').click(function(){
    $('#menulinks a').removeClass('mlnkactive');
    $(this).addClass('mlnkactive');
}

Upvotes: 1

Related Questions