Skip to content

Instantly share code, notes, and snippets.

@robertmclaws
Last active March 2, 2016 07:52
Show Gist options
  • Save robertmclaws/5724537 to your computer and use it in GitHub Desktop.
Save robertmclaws/5724537 to your computer and use it in GitHub Desktop.
Solution to allow Kendo.Mvc ClientTemplates on MVC4 when the AntiXssEncoder is enabled. Also works with any other MVC control experiencing an "Invalid Template" issue due to AntiXssEncoder.
TO USE:
Simply tack on .ToMvcClientTemplate() to the end of the outer-most MVC helper
that you're trying to turn into a template.
In this example: http://demos.kendoui.com/web/grid/detailtemplate.html, you
would add it after the last ToClientTemplate() that occurs before the script
section with the "function databound()" handler.
Note that returning an HtmlString instead of an MvcHtmlString will ensure you
don't have to call @Html.Raw() in your template to bypass the AntiXss encoding
that will be performed when MvcHtmlString.ToString() is called.
Feel free to lean hard on Telerik to get their ToClientTemplate() code changed
to include this technique.
using Kendo.Mvc.UI;
using System.Web;
using System.Web.Mvc;
using System.Web.Security.AntiXss;
using System.Web.Util;
namespace Your.Namespace.Here
{
public static class KendoMvcExtensions
{
public static IHtmlString ToMvcClientTemplate(this MvcHtmlString mvcString)
{
if (HttpEncoder.Current.GetType() == typeof (AntiXssEncoder))
{
var initial = mvcString.ToHtmlString();
var corrected = initial.Replace("\\u0026", "&").Replace("%23", "#").Replace("%3D", "=").Replace(" ", " ");
return new HtmlString(corrected);
}
return mvcString;
}
}
}
@JellyMaster
Copy link

Hi Thanks for this bit of code but I am a bit confused with how to implement this.

Is it possible to give a simple example on how to implement this. I would prefer to do this rather than disable antixssencoding in my app (even if it is an internal application).

Sorry if this a fairly obviously answer but I am still fairly new to the ways of MVC.

@krishnabharath
Copy link

hi! I have seen your reply and attempted to do the same in my project. But I don't know where to add the code that you have mentioned. Should I take a new class library in model and include the code that you have mentioned or I have to write the code in the KendoMVCExtensions.cs. But by default I didn't find this class file in my application. But when I removed the antiXss code in web.config file the application is working perfectly. Please help me to solve this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment