c# - 将 TagBuilder 核心方法从 ASP.NET MVC 5 迁移到 ASP.NET Core (.NET 5)
问题描述
我有一个使用 ASP.NET MVC 5 开发的 Web 应用程序,我必须将其迁移到 ASP.NET Core (.NET 5)。我有一些 HtmlHelper 的扩展方法来获取带有链接的字形图标:
public static MvcHtmlString GlyphiconActionLink(this HtmlHelper helper, string action, string controller, object parameters, string glyphiconTag, string title)
{
TagBuilder span = new TagBuilder("span");
span.MergeAttribute("class", $"glyphicon {glyphiconTag}");
span.MergeAttribute("title", title);
string url = UrlHelper.GenerateUrl(
null, action, controller, new RouteValueDictionary(parameters),
helper.RouteCollection, helper.ViewContext.RequestContext, true);
TagBuilder link = new TagBuilder("a");
link.MergeAttribute("href", url);
link.InnerHtml = span.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(link.ToString());
}
在 Razor pages 我可以写这个
@Html.GlyphiconActionLink("Details", "MyController", new { id = model.Id }, "glyphicon-pencil", "Show to details")
要获取此 HTML:
<a href="/mycontroller/details/1"><span class="glyphicon glyphicon-pencil" title="Details" /></a>
现在,在 .NET Core 中,此代码不起作用,它有很多错误。
我所做的改变:
- 返回值 from
System.Web.Mvc.MvcHtmlString
toMicrosoft.AspNetCore.Html.HtmlString
,正在返回return new HtmlString(link.ToString());
。 - 从
link.InnerHtml = span.ToString(TagRenderMode.SelfClosing)
到link.InnerHtml.Append(span.ToString(TagRenderMode.SelfClosing))
。
我遇到的错误是:
UrlHelper.GenerateUrl
: 'GenerateUrl' 由于其保护级别而无法访问。helper.RouteCollection
:“HtmlHelper”不包含“RouteCollection”的定义。helper.ViewContext.RequestContext
:“ViewContext”不包含“RequestContext”的定义。span.ToString(TagRenderMode.SelfClosing)
: 方法 'ToString' 没有重载需要 1 个参数。
你知道如何迁移它吗?
解决方案
推荐阅读
- python - matplotlib 对数 y 轴格式
- websocket - 在 Rancher 的 LoadBalancer 中删除了 WebSocket 连接
- javascript - 使用 fetch api 发布 json 数据失败
- django - 如何在 Django-Rest 中序列化嵌套模型
- python - python TypeError:字符串索引必须是整数json
- angular - VM Clarity - clrForm 选择输入
- xaml - 如何使用动态计数 Xamarin.Forms 创建滑块
- reactjs - 将 sweetalerts2 与 api 调用一起使用
- sql - google bigquery SQL group by 聚合函数
- javascript - 在嵌套数组中搜索 JavaScript 中的空对象