这就是我现在所拥有的,它运行良好:
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current"} : null)我想要做的就是给它一个ID,即使条件为假,也要保留这个ID。所以就像这样:
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", id = "Home" } : new { id = "Home" })另外,我想设置一个onclick()函数,而不是直接点击控制器。
发布于 2013-03-22 17:13:30
@Html.ActionLink()辅助对象是为了创建指向控制器的链接而创建的。但是对于为它分配onclick()函数的问题,有一个非常简单的解决方法。
示例:(我假设在onclick事件中使用javascript函数)
<script type="text/javascript">
function foo(string){
alert(string);
return false; //Very Important
}
</script>因此,对于ActionLink,您可以放入:
@Html.ActionLink("Home", "", "", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home",onclick="javascript:foo('foo2');" } : new { @id = "Home" })注意JS函数中的return false部分。如果您不希望页面在单击ActionLink后刷新,这一点非常重要。此外,在ActionLink的ActionName和RouteValues中输入空字符串也会阻止它调用控制器。
至于你关于ID的问题的第一部分,记得把@放在id之前:
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home" } : new { @id = "Home" })因此,最终的ActionLink将如下所示:
@Html.ActionLink("Home", "", "", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home",onclick="javascript:somefunction()" } : new { @id = "Home" })这样说来,我不确定您是否可以指定: new {@id = "Home"}
因此,为了解决这个问题,我建议这样做:
@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;"})
}https://stackoverflow.com/questions/15555343
复制相似问题