ryan ryan - 28 days ago 21
C# Question

KendoUI, can you call C# methods within Template() or ClientTemplate()?

I need to generate a URL to display in a table I am creating with Kendo grid. The problem is that this URL must be generated from models ID. For example:

string aUrl = Url.GenerateUrl(person.Id);


However its tricky to use this with a kendo grid as something like:

...Kendo()
.Grid<Person>()
.Name("gridPeople")
.Columns(columns =>
{
columns.Bound(p => p.Name);
columns.Bound(p => Url.GenerateUrl(p.Id));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("ReadPeople", "Person"))
)


Will result in the error:

bound columns require a field or property access expression


I'm unsure how to implement this. I have tried:

columns.Bound(p => p.Id).ClientTemplate(@Url.GenerateUrl("#: Id #"))


and

columns.Bound(p => p.Id).ClientTemplate("@Url.GenerateUrl(#: Id #)")


but neither work. The second one comes close, but prints the text "@Url.Generate(XXXX-SOME-IDNO)" with the Ids being properly populated from the model. But i want it to print the result of that function, not print out the actual programming statement :(

Answer

I believe Url.GeneralUrl is evaluated only once when the page is rendered since you are using AJAX for your datasource. So your client template is the result of calling Url.GenerateUrl("#: Id #") and I have no clue what that client template would be but it sounds like it's not working for you.

Instead, try adding the URL to your grid's model and populate it server-side (your controller can create a UrlHelper, do an internet search if you don't know how).

As an aside, you don't need the '@' symbol to write out C# code when you are already in C# context. So it would be

columns.Bound(p => p.Id).ClientTemplate(Url.GenerateUrl("#: Id #"))

instead of

columns.Bound(p => p.Id).ClientTemplate(@Url.GenerateUrl("#: Id #"))
Comments