4

ダイナミクス ExpandoObjects のコレクションで Telerik MVC を使用しようとしています。

コントローラーは次のとおりです。

[GridAction]
public ActionResult TestDiario()
{
        var result = new List<dynamic>();

        dynamic diarioModel = new ExpandoObject();

        var dictionary = (IDictionary<string, object>)diarioModel;

        dictionary.Add("ID", 1);
        dictionary.Add("AlunoID", 12781);
        dictionary.Add("DAY05CLASS1", true);
        dictionary.Add("DAY05CLASS2", true);
        dictionary.Add("DAY07CLASS1", true);
        dictionary.Add("DAY08CLASS1", true);

        result.Add(diarioModel);
        return View(result);
}

ビューは次のとおりです。

@using Telerik.Web.Mvc.UI

@model IEnumerable<dynamic>

@{
    ViewBag.Title = "TestDiario";
}

@(Html.Telerik().Grid(Model).Name("Grid")
    .DataKeys(dataKeys => dataKeys.Add("ID"))
    .Columns(columns => 
    { 
        columns.Bound("MatAnoID").Visible(true);
        columns.Bound("AlunoID");
        columns.Bound("NroClasse");
        columns.Bound("Aluno");

        var dictionary = (IDictionary<string, object>)Model;
        foreach (var property in (IDictionary<String, Object>)dictionary)
        {
            if (property.Key.ToString().Remove(3) == "DAY")
            {
                columns.Bound(property.Key);
            }
        }
    })
    .Pageable()
    .Sortable()
    .Groupable()
    .Filterable()

)

ループ foreach は、DAY 文字列で始まるダイナミクス フィールドを取得します。

プロジェクトを実行すると、次のエラーが表示されます。

{"型付きオブジェクト 'System.Collections.Generic.List 1[System.Object]' to type 'System.Collections.Generic.IDictionary2[System.String,System.Object]' を変換することはできません。"}

ループ スルー フィールドを持つ Telerik MVC コントロールで動的オブジェクトを使用する方法はありますか?

4

1 に答える 1

3

はい、できます。かなり接近していましたが、いくつかの間違いを犯しました。

1) モデルは expando オブジェクトではないため、タイプ IDictionary ではありません。ダイナミックの一覧です。

これはちょっとしたハックですが、その問題を解決するために、列挙可能な要素の最初の (またはデフォルトの) 要素を取得し、それから辞書を作成しました。

2) expando オブジェクトにプロパティとして存在しない列をバインドしようとしています。

それらをコメントアウトしました。

3) 「DAY」で始まるキーを探していたと思います。列名から「DAY」を削除したい場合は、サンプル コードを微調整できます。

それ以外は正常に動作します:

@(Html.Telerik().Grid(Model).Name("Grid")
    .DataKeys(dataKeys => dataKeys.Add("ID"))
    .Columns(columns => 
    { 
        //NOTE: some of these columns are not valid because you didn't include them as properties
        //columns.Bound("MatAnoID").Visible(true);
        //columns.Bound("NroClasse");
        //columns.Bound("Aluno");

        columns.Bound("AlunoID");

        var first = Model.FirstOrDefault();
        if (first != null) {
            var dictionary = (IDictionary<string, object>)first;
            foreach (var property in dictionary) {
                string key = property.Key.ToString();
                if (key.StartsWith("day", StringComparison.InvariantCultureIgnoreCase)) {
                    columns.Bound(property.Key);
                }
            }
        }

    })
    .Pageable()
    .Sortable()
    .Groupable()
    .Filterable()
)
于 2012-11-25T17:38:13.040 に答える