【问题标题】:How to Attribute encode a PartialView in MVC (Razor)如何在 MVC (Razor) 中对 PartialView 进行属性编码
【发布时间】:2012-08-23 13:42:19
【问题描述】:

我正在使用 PartialViews 在我的 ASP.NET MVC 应用程序中存储工具提示的 HTML。我最初的想法是 Razor 会自动对 HTML 中引号之间的任何内容进行属性编码。不幸的是,情况似乎并非如此,所以我现在的解决方法是使用单引号来封装我的 PartialViews HTML。如下:

<div class="tooltip" title='@Html.Partial("_MyTooltipInAPartial")'>Some content</div>

这很有效,但如果我的 PartialView 中有任何单引号,我显然会遇到问题。

有人知道解决这个问题的正确方法吗?我得到的最接近的是以下:

<div class="tooltip" title="@HttpUtility.HtmlAttributeEncode(Html.Partial("_MyTooltipInAPartial"))">Some content</div>

不幸的是,这并不完全有效,因为 Partial 的输出是 MvcHtmlString 而不是直字符串。

谁有更好的主意?

【问题讨论】:

  • @HttpUtility.HtmlAttributeEncode(Html.Partial("_MyTooltipInAPartial").ToHtmlString()) 呢?
  • 谢谢 - 我试过这个但 VS 抱怨:-(

标签: asp.net-mvc-3 razor attributes partial-views encode


【解决方案1】:

感谢 nemesv 的建议 - 它没有成功。经过一番思考,我最终通过编写一个名为 PartialAttributeEncoded 的 HTML 辅助方法来解决自己的问题。

对于任何感兴趣的人,这里是你如何使用帮助器:

<div class="tooltip" title="@Html.PartialAttributeEncoded("_MyTooltipInAPartial")">Some content</div>

这是助手:

using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace My.Helpers
{
    /// <summary>
    /// MVC HtmlHelper extension methods - html element extensions
    /// </summary>
    public static class PartialExtensions
    {
        /// <summary>
        /// Allows a partial to be rendered within quotation marks.
        /// I use this with jQuery tooltips where we store the tooltip HMTL within a partial.
        /// See example usage below:
        /// <div class="tooltip" title="@Html.PartialAttributeEncoded("_MyTooltipInAPartial")">Some content</div>
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="partialViewName"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static MvcHtmlString PartialAttributeEncoded(
          this HtmlHelper helper,
          string partialViewName,
          object model = null
        )
        {
            //Create partial using the relevant overload (only implemented ones I used)
            var partialString = (model == null)
                ? helper.Partial(partialViewName)
                : helper.Partial(partialViewName, model);

            //Attribute encode the partial string - note that we have to .ToString() this to get back from an MvcHtmlString
            var partialStringAttributeEncoded = HttpUtility.HtmlAttributeEncode(partialString.ToString());

            //Turn this back into an MvcHtmlString
            var partialMvcStringAttributeEncoded = MvcHtmlString.Create(partialStringAttributeEncoded);

            return partialMvcStringAttributeEncoded;
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多