【问题标题】:ASP.NET MVC 3: Extension method on UrlHelper/HtmlHelper encodes to HTMLASP.NET MVC 3:UrlHelper/HtmlHelper 上的扩展方法编码为 HTML
【发布时间】:2011-11-19 12:16:45
【问题描述】:

我已经为 UrlHelper 编写了一些扩展方法,以便更轻松地加载 , 或标记。但是,它似乎在浏览器中呈现为文字文本。这是我所拥有的:

public static string Script(this UrlHelper helper, string scriptPath)
        {
            return string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath));
        }

这是我的 .cshtml 代码:

@section HeadContent
{
    @Url.Style("MyStyleName")
    @Url.Script("MyScriptName")
    @Url.MetaKeywords("My Keywords")
    @Url.MetaDescription("Some Description")
}

它在浏览器中显示为&amp;lt;script [etc, etc]&amp;gt;

如果我不使用扩展方法,它会按预期正常工作......我怎样才能让它与我的扩展一起工作?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    试试这个:

    public static string Script(this UrlHelper helper, string scriptPath)
    {
        return MvcHtmlString.Create(string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath)));
    }
    

    【讨论】:

    • 谢谢你,朋友!这正是我所需要的。唯一的问题是返回类型也必须是 MvcHtmlString。再次感谢。
    • 欢迎朋友!请考虑该答案已被其他人接受以了解正确答案。
    • 确实如此。我正在等到我能够接受答案......它说我不能再做 3 分钟!疯狂的东西......
    【解决方案2】:

    所有 HTML 助手都需要返回 MvcHtmlString。如果您只返回一个字符串,它将被视为不受信任的值,并将进行 HTML 编码。

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多