在 ASP.NET MVC Html.ActionLink 中包含锚标记

在 ASP.NET MVC 中,我试图创建一个包含锚标记的链接(也就是说,将用户指向一个页面,以及该页面的特定部分)。

我尝试创建的 URL 应该如下所示:

<a href="/category/subcategory/1#section12">Title for a section on the page</a>

我的路由是按照标准设置的:

routes.MapRoute("Default", "{controller}/{action}/{categoryid}");

我使用的 action 链接语法是:

<%foreach (Category parent in ViewData.Model) { %>
<h3><%=parent.Name %></h3>
<ul>
<%foreach (Category child in parent.SubCategories) { %>
<li><%=Html.ActionLink<CategoryController>(x => x.Subcategory(parent.ID), child.Name) %></li>
<%} %>
</ul>
<%} %>

我的控制器方法如下:

public ActionResult Subcategory(int categoryID)
{
//return itemList


return View(itemList);
}

以上正确返回的 URL 如下:

<a href="/category/subcategory/1">Title for a section on the page</a>

我不知道怎么把 # 第12部分加进去。“ section”单词只是我用来分解页面部分的约定,而12是子类别的 ID,即 child.ID。

我怎么能这么做?

149634 次浏览

我可能会手动构建这个链接,如下所示:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

ActionLink 的重载采用 碎片参数。传递“ section 12”作为你的片段将会得到你想要的行为。

例如,调用 ActionLink 方法(HtmlHelper,String,String,String,String,String,String,Object,Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

如果您将 ActionFilter 应用到 SubCategory 操作方法,我的解决方案将会起作用,只要您总是希望将用户重定向到相同的书签:

Http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

它修改 HTML 缓冲区并输出一小段 javascript 来指示浏览器添加书签。

当然,您可以修改 javascript 来手动滚动,而不是在 URL 中使用书签!

希望对你有所帮助:)

我不记得在哪个版本的 ASP.NET MVC (我相信是 ASP.NET MVC 3 +)/Razor 中引入了参数标签声明或者其他什么(参数: x)特性,但是对我来说这绝对是在 ASP.NET MVC 中用锚建立链接的正确方法。

@Html.ActionLink("Some link text", "MyAction", "MyController", protocol: null, hostName: null, fragment: "MyAnchor", routeValues: null, htmlAttributes: null)

甚至连 这个答案的 Ed Blackburn 反模式论点也无法与之相比。

这是现实生活中的例子

@Html.Grid(Model).Columns(columns =>
{
columns.Add()
.Encoded(false)
.Sanitized(false)
.SetWidth(10)
.Titled(string.Empty)
.RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));


}).WithPaging(200).EmptyText("There Are No Items To Display")

目标页面有 TABS

<ul id="myTab" class="nav nav-tabs" role="tablist">


<li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
</ul>

我做到了这一点,它工作的重定向到其他视图 我认为如果你在它之后添加 # sectionLink,它将工作

<a class="btn yellow" href="/users/Create/@Model.Id" target="_blank">
Add As User
</a>

我就是这么做的:

<a href="@Url.Action("Index","Home")#features">Features</a>