我想知道是否可以在调用方法时有条件地添加参数。
例如,我在我的 Site.Master 中渲染了一堆链接(总共六个)用于导航:
<%= Html.ActionLink("About", "About", "Pages") %> |
<%= Html.ActionLink("Contact", "Contact", "Pages") %>
<%-- etc, etc. --%>
如果链接在该页面上,我想为链接添加一个“选定”的 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 这样的东西,它利用我的路线而不是硬编码标签。