Вопрос

This is what I have right now which works fine:

@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current"} : null)

What I'm trying to do is give it an ID as well and keep that ID even if the condition is false. So something like this:

@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", id = "Home" } : new { id = "Home" })

Also, I want to set an onclick() function and not direct the click to a controller.

Это было полезно?

Решение

AFAIK, the @Html.ActionLink() helper is made just for the purpose of creating the link to a controller. But there is a very simple workaround for your problem of assigning an onclick() function to it.

Example: (I am assuming javascript function for onclick event)

<script type="text/javascript">
  function foo(string){
    alert(string);
    return false; //Very Important
  }
</script>

So then for in the ActionLink you can put:

@Html.ActionLink("Home", "", "", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home",onclick="javascript:foo('foo2');" } : new { @id = "Home" })

Note the return false part in the JS function. This is very important if you do NOT want your page to refresh after clicking on the ActionLink. Also entering empty strings into the ActionName and RouteValues of the ActionLink stops it from calling a controller.

As for the first part of your question of the ID remember to put the @ before the id:

@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home" } : new { @id = "Home" })

So the final ActionLink would look something like this:

@Html.ActionLink("Home", "", "", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home",onclick="javascript:somefunction()" } : new { @id = "Home" })

Having put that I am unsure if you can specify the : new {@id = "Home"}

So to work around that I would suggest something like this:

@if(ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home)
{
  @Html.ActionLink("Home", "", "", null, new { @class = "current", @id = "Home", onclick="javascript:alert('True');return false;" })
}
else
{
//Not sure what you would like to put in the else clause
@Html.ActionLink("Home", "", "", null, new { @class = "current", @id = "Home", onclick="javascript:alert('False');return false;"})
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top