asp.net-mvc-3
  • razor
  • attributes
  • partial-views
  • encode
  • 2012-08-23 42 views 2 likes 
    2

    我正在使用PartialViews在ASP.NET MVC應用程序中存儲工具提示的HTML。我最初的想法是,Razor會自動將我HTML中引號之間的所有內容進行屬性編碼。不幸的是,這似乎不是這種情況,所以我現在的解決方法是使用單引號來封裝我的PartialViews HTML。如下:如何在MVC(剃刀)中對PartialView進行屬性編碼

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

    這工作只是丹迪,但顯然我有問題,如果我的PartialView中有任何單引號。

    有誰知道正確的方法來解決這個問題嗎?我得到的最接近的是如下:

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

    不幸的是,因爲部分的輸出是MvcHtmlString而不是直接串這完全不是那麼回事。

    任何人有更好的主意嗎?

    +2

    什麼'@ HttpUtility.HtmlAttributeEncode(Html.Partial( 「_ MyTooltipInAPartial」)。 ToHtmlString())'? – nemesv

    +0

    謝謝 - 我試過這個,但VS抱怨:-( –

    回答

    2

    感謝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; 
         } 
        } 
    } 
    
    +0

    我最終把它變成了一篇博客文章,你可以在這裏找到:http://icanmakethiswork.blogspot.co.uk/2012/08/how-to-attribute-編碼 - partialview-in.html –

    相關問題