首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Html.ActionLink内联if语句

Html.ActionLink内联if语句
EN

Stack Overflow用户
提问于 2013-03-22 02:28:58
回答 1查看 3.5K关注 0票数 0

这就是我现在所拥有的,它运行良好:

代码语言:javascript
复制
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current"} : null)

我想要做的就是给它一个ID,即使条件为假,也要保留这个ID。所以就像这样:

代码语言:javascript
复制
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", id = "Home" } : new { id = "Home" })

另外,我想设置一个onclick()函数,而不是直接点击控制器。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-22 17:13:30

@Html.ActionLink()辅助对象是为了创建指向控制器的链接而创建的。但是对于为它分配onclick()函数的问题,有一个非常简单的解决方法。

示例:(我假设在onclick事件中使用javascript函数)

代码语言:javascript
复制
<script type="text/javascript">
  function foo(string){
    alert(string);
    return false; //Very Important
  }
</script>

因此,对于ActionLink,您可以放入:

代码语言:javascript
复制
@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之前:

代码语言:javascript
复制
@Html.ActionLink("Home", "Index", "Home", null, (ViewBag.SelectedPage == CurrentPageEnums.SelectedViewEnum.Home) ? new { @class = "current", @id = "Home" } : new { @id = "Home" })

因此,最终的ActionLink将如下所示:

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

这样说来,我不确定您是否可以指定: new {@id = "Home"}

因此,为了解决这个问题,我建议这样做:

代码语言:javascript
复制
@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;"})
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15555343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档