具有asp-controller和asp-action属性的锚不会显示为链接 [英] Anchors with asp-controller and asp-action attribute don't get rendered as links

查看:453
本文介绍了具有asp-controller和asp-action属性的锚不会显示为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Razor语法:

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

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

"Home"链接可以很好地呈现,但是手动呈现的<a>字符串不会变成有效的链接.

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

LinkTree()的实现方式如下:

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

当我用@link.LinkTree()打印链接时,输出中包含一行,只显示了所显示的代码,而没有链接.

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

使用@Html.Raw(link.LinkTree())可以获取链接,但是它们是不可单击的,因为它们实际上将asp-controller/asp-action属性打印到HTML,而不是生成href.

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?

推荐答案

Razor引擎未处理从方法返回的HTML代码或实际上从方法返回的任何文本,因此您不能在此处使用HTML标记帮助器.

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.

例如,您可以将IHtmlHelper对象传递到您的方法中:

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

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

然后在您的方法中,只需使用ActionLink重载来创建链接:

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);
}

或者,您也可以在对象上公开这三个属性,并使用Razor正确编写链接:

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>
}

这篇关于具有asp-controller和asp-action属性的锚不会显示为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆