有条件地将 htmlAttributes 添加到 ASP.NET MVC Html.ActionLink
我想知道是否可以有条件地在方法调用中添加参数。
例如,我正在渲染一堆链接(总共六个)以在我的 Site.Master 中进行导航:
<%= Html.ActionLink("About", "About", "Pages") %> |
<%= Html.ActionLink("Contact", "Contact", "Pages") %>
<%-- etc, etc. --%>
如果链接位于该页面上,我想为该链接包含一个 CSS 类“selected”。所以在我的控制器中我返回这个:
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 这样的东西,它可以利用我的路线,而不是对标签进行硬编码。
I'm wondering if it's possible to conditionally add a parameter in a call to a method.
For example, I am rendering a bunch of links (six total) for navigation in my Site.Master:
<%= Html.ActionLink("About", "About", "Pages") %> |
<%= Html.ActionLink("Contact", "Contact", "Pages") %>
<%-- etc, etc. --%>
I'd like to include a CSS class of "selected" for the link if it's on that page. So in my controller I'm returning this:
ViewData.Add("CurrentPage", "About");
return View();
And then in the view I have an htmlAttributes dictionary:
<% Dictionary<string,object> htmlAttributes = new Dictionary<string,object>();
htmlAttributes.Add("class","selected");%>
Now my only question is how do I include the htmlAttributes for the proper ActionLink. I could do it this way for each link:
<% htmlAttributes.Clear();
if (ViewData["CurrentPage"] == "Contact") htmlAttributes.Add("class","selected");%>
<%= Html.ActionLink("Contact", "Contact", "Pages", htmlAttributes) %>
But that seems a little repetitive. Is there some way to do something like this psuedo code:
<%= Html.ActionLink("Contact", "Contact", "Pages", if(ViewData["CurrentPage"] == "Contact") { htmlAttributes }) %>
That's obviously not valid syntax, but is there a correct way to do that? I'm open to any totally different suggestions for rendering these links. I'd like to stay with something like ActionLink that takes advantage of using my routes though instead of hard coding the tag.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有三个选项:
Here are three options: