【问题标题】:Html.ActionLink inline if statementHtml.ActionLink 内联 if 语句
【发布时间】:2013-03-21 18:28:57
【问题描述】:

这就是我现在所拥有的,效果很好:

@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() 函数,而不是将点击定向到控制器。

【问题讨论】:

    标签: asp.net-mvc-4 html.actionlink


    【解决方案1】:

    AFAIK,@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;"})
    }
    

    【讨论】:

    • 我不得不向两边添加类和 id,但它确实有效。我还必须将 return false 放在 actionlink 中,以使页面不刷新。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2022-07-07
    • 2017-08-18
    • 2011-02-19
    • 2017-03-24
    相关资源
    最近更新 更多