【问题标题】:Change URL string to hyperlink in C# ASP.NET MVC in View在视图中将 URL 字符串更改为 C# ASP.NET MVC 中的超链接
【发布时间】:2020-03-20 01:03:24
【问题描述】:

我正在尝试将 URL 转换为短超链接。我正在使用 .NET Core MVC。如何在此视图中将链接字符串显示为超链接?我想在 View 中而不是在 Controller 端执行此操作。

message.MessageText 包含可能包含或不包含 URL 的消息。正则表达式部分已经在工作,它与消息中的任何 URL 匹配。当页面加载时,超链接显示为字符串而不是链接。是否可以从 View 执行此操作,还是必须将代码添加到控制器?

<html>
    <div>
        @{
            Regex rx = new Regex(@"^(https:|http:|www\.)\S*");
            var matches = rx.Matches(message.MessageText);
            string URLMessage = Regex.Replace(message.MessageText,
                                              @"(https:|http:|www\.)\S*",
                                              delegate (Match match)
                                              {
                                                string v = match.ToString();
                                                return "<a href='" + v + "' target='_blank' title='" + v + "'>123</a>";
                                              });
        }                                            

        @URLMessage                                             
    </div>
</html>

【问题讨论】:

    标签: c# html razor hyperlink asp.net-core-mvc


    【解决方案1】:

    你可以使用@Html.Raw(string)来渲染html字符串:

    @Html.Raw(URLMessage)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多