【问题标题】:ASP.NET Core 3.1 Razor - Is it possible to turn a String into a Hyperlink using Html.RawASP.NET Core 3.1 Razor - 是否可以使用 Html.Raw 将字符串转换为超链接
【发布时间】:2020-05-09 04:36:18
【问题描述】:

是否可以使用 Html.Raw 将字符串转换为超链接。这个代码是什么? 我正在尝试将 <a> 标签嵌入到 Razor 页面中,其中包含以下内容:

@{
  string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" asp- 
  area=\"Test\" asp-controller=\"Test\" asp-action=\"ViewFile\" asp-route-Id=1> View File Test</a>";  
 }
@Html.Raw(strText)

我的页面只显示“查看文件测试”,没有链接。

当我在浏览器中查看页面源代码时,我看到以下内容:

<title>Link Test</title><a class="nav-link text-dark" target="_new" asp-area="Test" asp-controller="Test" asp-action="ViewFile" asp-route-Id=1> View File Test</a>

当我复制以上内容并将其粘贴到我的剃须刀页面时,一切正常。

只是为了好玩,我还尝试了以下方法并得到了相同的结果:

@{
  string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" asp- 
  area=\"Test\" asp-controller=\"Test\" asp-action=\"ViewFile\" asp-route-Id=1> View File Test</a>";  
 }
<text>@strText</text>

下面的例子可以正常工作,但上面的例子不行。我想这可能与嵌入的引号有关

@{
  string strText = "My Text <a href=\"http://www.google.com\">My link</a>.";  
 }
@Html.Raw(strText)

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    对于 HtmlHelper.Raw Method ,参数是 HTML 标记,但 asp-areaasp-controllerAnchor Tag Helper attributes。从方法返回的 HTML 代码或实际上任何文本都不会由 Razor 引擎处理,因此您不能在此处使用 HTML 标签助手。

    您可以尝试使用@Html.ActionLink@Url.Action 辅助方法,如图所示:

    @{
       string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" href=\""+Url.Action("ViewFile","Test" ,new { Area="Test",Id=1})+"\" >View File Test</a>";
    }
    

    生成的网址将是https://localhost:44348/Test/Test/ViewFile?Id=1

    如下注册路由:

    app.UseEndpoints(endpoints =>
    {
          endpoints.MapControllerRoute(
                   name: "areaRoute",
                   // if you don't have such an area named as `areaName` already, 
                   //    don't make the part of `{area}` optional by `{area:exists}`
                   pattern: "{area}/{controller=Home}/{action=Index}");
           endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
     });
    

    参考:

    https://stackoverflow.com/a/35579040/10201850

    https://stackoverflow.com/a/53147778/10201850

    【讨论】:

      【解决方案2】:

      使用 asp 标签的解决方案不起作用的主要原因是它们(标签助手)在运行时被编译到您现有的视图中。 在运行时编译时,您的字符串被编译为字符串,其中的标签显然被忽略了,因为编译器不知道它们。 但是当你使用像锚标记这样的 html 属性时,它会正常工作,因为它会被你的浏览器解析。

      【讨论】:

        【解决方案3】:

        请记住,在 Razor 中,标签的带有 asp 前缀的属性以某种方式呈现在服务器端。此属性/属性不是来自 HTML5。

        回答:可以,但必须是有效的 HTML。

        【讨论】:

          猜你喜欢
          • 2021-09-25
          • 2014-10-26
          • 1970-01-01
          • 1970-01-01
          • 2017-09-12
          • 2019-06-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多