基于标志的条件绑定

Conditional binding based on flag

我有一个带有 AJAX 数据源的 Kendo-UI 网格。 我正在使用 ASP.NET-MVC。

模型看起来像这样:

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; }
}

如果 bool IsTextQuestion 为真,我希望用户有一个绑定到字段 TextAnswer 的 incell 文本框。如果该值为 false 我想将其绑定到 NummericAnswer 属性.

我该怎么做? 我想我需要使用模板或客户端模板?

根据 Telerik 文档:

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

来自他们的 doco 的几个片段大致适合您的情况(但未经测试!)展示了如何完成。首先作为一些内联 javascript 代码:

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

或者通过调用 javascript 函数:

 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>

查看常见问题解答项目 Grid Frequently Asked Questions: Displaying Values 以获取更多示例。