dotcom ontwikkel
dotcom ontwikkel

Reputation: 33

Conditional binding based on flag

I have a Kendo-UI Grid with an AJAX datasource. I am working with ASP.NET-MVC.

The model looks like this:

public class QuestionModelPlayer
{
    public Guid Id { get; set; }
    public String Description { get; set; }
    public string TextAnswer { get; set; }
    public int? NummericAnswer { get; set; }
    public bool isTextQuestion { get; set; }
}

If the bool IsTextQuestion is true I want the users have an incell textbox which binds to the field TextAnswer. If the value is false I want to bind it to the NummericAnswer property.

How can I do this? I think i need to use a Template or ClientTemplate?

Upvotes: 3

Views: 854

Answers (1)

slugster
slugster

Reputation: 49985

According to the Telerik documentation:

If the grid is ajax bound use the ClientTemplate method. The value should be a string which represents a valid Kendo Template.

A couple of snippets sourced from their doco and roughly adapted to your situation (but not tested!) show how it can be done. First as some inline javascript code:

columns.Bound(q => q.isTextQuestion)
       .ClientTemplate (
    "# if (isTextQuestion == true) { #" +
        "#: TextAnswer #" +
    "# } else { #" +
        "#: NummericAnswer #" +
    "# } #"
);

or alternatively by calling a javascript function:

 columns.Bound(q => q.isTextQuestion)
        .ClientTemplate("#= getAnswer(data) #");


<script>
    function getAnswer(question) {

        var html = kendo.format( "<text>{0}</text>"
                                ,question.isTextQuestion 
                                    ? question.TextAnswer 
                                    : question.NummericAnswer 
                                );

        return html;
    }
</script>

Check the FAQ item Grid Frequently Asked Questions: Displaying Values for lots more examples.

Upvotes: 4

Related Questions