Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping +(plus) sign in Kendo grid ASP.NET MVC ClientTemplate

I've having a problem defining a ASP.NET MVC ClientTemplate for a column in a Kendo grid because the '+' sign is being stripped out, which causes the client-side generated template to fail because of bad syntax.

My ClientTemplate is:

c.Template(@<text></text>).ClientTemplate("#='Hello' + Name#")

In the client, however, this gets reduced to:

template: "#='Hello'   Name#"

i.e. the plus sign has been rendered as a space (similar to URL encoding I guess). The template works perfectly if I use from JS directly (see this JSBin).

Does anyone know how I can escape the + sign so I can use it in the ClientTemplate?

I have tried escaping using '\\+' (gets rendered as '\'), '\+' (invalid C#), &#43; (same as +, although others such as &#44;' work fine).

Any ideas? Thanks.

For reference I'm using Razor markup and Q2 2012 Kendo release (can't use Q3 yet as limited by jQuery version as we're upgrading from Telerik)

NOTE: before anyone asks why I'm doing this, my ClientTemplate is actually more complex but this is a simplified example to illustrate the problem :-)

like image 619
Tim Croydon Avatar asked Jan 17 '13 16:01

Tim Croydon


3 Answers

I checked the source code1, the MVC wrapper is calling HttpUtility.UrlDecode on all templates before it renders them to JS. So to escape your + sign (or any other reserved URL character), use percent encoding. In this case %2B.

c.Template(@<text></text>).ClientTemplate("#='Hello' %2B Name#")

1 v2013.3, src\Kendo.Mvc\Kendo.Mvc\UI\Grid\Columns\GridColumnBase.cs, line 135. I suspect this is a bug and they meant to call HttpUtility.UrlEncode.

like image 163
just.another.programmer Avatar answered Oct 22 '22 20:10

just.another.programmer


Found a solution (possibly more of a workaround). Rather than writing inline JavaScript I moved my code to a separate JS function and called that from the template code, e.g.:

#=myFunctionToDoComplicatedStuff(Name)#

To be honest, for reasons of testability, reuse and general good practice this is probably the approach that should be taken anyway. It's a bit annoying for something trivial though!

like image 29
Tim Croydon Avatar answered Oct 22 '22 19:10

Tim Croydon


If you just need a simple solution for doing concatenation in your ClientTemplate that avoids the encoding issue with plus signs, you can use the javascript concat function like this:

c.Template(@<text></text>).ClientTemplate("#='Hello'.concat(Name)#")
like image 42
DanO Avatar answered Oct 22 '22 19:10

DanO