Anchors with asp-controller and asp-action attribute don't get rendered as links

≡放荡痞女 提交于 2020-06-27 13:17:15

问题


In this Razor syntax:

<a asp-controller="Home" asp-action="Index">Home</a>

@foreach (LinkNodeModel link in Model.ControlActions)
{
    link.LinkTree();
}

The "Home" link renders just fine, but the manually rendered <a> strings don't get turned into a valid link.

LinkTree() is implemented like this:

return $"<a asp-controller=\"{Controller}\" asp-action=\"{Action}\">{Name}</a>";

When I print the links with the @link.LinkTree(), the output contains a line with just the code displayed, which doesn't link.

With @Html.Raw(link.LinkTree()) I get the links, but they are not clickable as they actually print the asp-controller/asp-action attributes to the HTMLinstead of generating the href.

Is it possible to generate and render links like these dynamically? And if so, how?


回答1:


HTML code, or actually any text, returned from methods is not processed by the Razor engine, so you cannot use HTML tag helpers here.

What you can do however is call the “classic” HtmlHelper.ActionLink method (or one of the more helpful extension methods) to return a properly rendered a tag for a controller action.. Since it’s just a normal method, you can call it within your own method.

For example, you could pass in the IHtmlHelper object into your method:

@foreach (LinkNodeModel link in Model.ControlActions)
{
    link.LinkTree(@Html);
}

And then in your method, just use a ActionLink overload to create the link:

public IHtmlContent LinkTree(IHtmlHelper helper)
{
    return helper.ActionLink(Name, Action, Controller);
}

Alternatively, you can also expose those three properties on your object and write the link properly with Razor:

@foreach (LinkNodeModel link in Model.ControlActions)
{
    <a asp-controller="@link.Controller" asp-action="@link.Action">@link.Name</a>
}



回答2:


The tag helpers, which convert <a asp-controller="$controller" asp-action="$action"> to <a href="/$controller/$action"> are opt-in as described in Introducing TagHelpers in ASP.NET MVC 6, so you'll need to configure your application to use them:

This is best placed in the _ViewImports.cshtml file, which is a new Razor file also introduced in ASP.NET 5:

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"


来源:https://stackoverflow.com/questions/35578626/anchors-with-asp-controller-and-asp-action-attribute-dont-get-rendered-as-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!