我在想是否有可能在调用方法时有条件地添加参数。
例如,我正在为我的Site.Master中的导航呈现一堆链接(总共六个)。
例如,我正在为我的Site.Master中的导航呈现一堆链接(总共六个)。
<%= Html.ActionLink("About", "About", "Pages") %> |
<%= Html.ActionLink("Contact", "Contact", "Pages") %>
<%-- etc, etc. --%>
我想在链接所在的页面上包含一个名为“selected”的CSS类。所以在我的控制器中,我返回了以下内容:
ViewData.Add("CurrentPage", "About");
return View();
然后在视图中,我有一个htmlAttributes字典:
<% Dictionary<string,object> htmlAttributes = new Dictionary<string,object>();
htmlAttributes.Add("class","selected");%>
现在我的唯一问题是如何为正确的ActionLink包含htmlAttributes。我可以为每个链接这样做:
<% htmlAttributes.Clear();
if (ViewData["CurrentPage"] == "Contact") htmlAttributes.Add("class","selected");%>
<%= Html.ActionLink("Contact", "Contact", "Pages", htmlAttributes) %>
但这似乎有点重复。有没有什么方法可以像下面的伪代码一样处理:
<%= Html.ActionLink("Contact", "Contact", "Pages", if(ViewData["CurrentPage"] == "Contact") { htmlAttributes }) %>
这显然不是有效的语法,但是否有正确的方法来实现它?我可以接受任何完全不同的建议来呈现这些链接。我希望使用类似ActionLink的东西,它利用我的路由而不是硬编码标记。
disabled
属性不起作用,因为浏览器会在disabled=""
的情况下禁用 HTML 元素。编写自己的 HTML 辅助方法似乎是唯一的解决方案。 - arviman