Created
August 24, 2012 11:31
-
-
Save johnnyreilly/3449462 to your computer and use it in GitHub Desktop.
HTML Helper for rendering attribute encoded PartialViews
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment