如何将嵌套的 json 绑定到 Kendo Dropdownlist asp .net core?

问题描述

我尝试在 kendo dropdownlist asp dot net core 中进行服务器绑定。但是如果返回的json是嵌套格式,则数据不会绑定

public async Task<IActionResult> GetlistofMenuCategory()
            {
                try
                {
                    var Categories = (await _menuCategoryRepo.GetAllAsync().ConfigureAwait(true));

                var menuCategoriesResponseData = Categories.Select(i => new
                { categoryId = i.CategoryId,name = i.Name}).ToList();
                return await this.SendSuccess(menuCategoriesResponseData).ConfigureAwait(true);
            }
            catch (Exception Ex)
            {
                _logger.LogError(Ex,Ex.Message);
                return await this.SendError(Ex.Message).ConfigureAwait(true);
            }
        }

它以这种格式返回json

"data":[{"categoryId":1,"name":"Momo"}]}

我的查看代码将数据绑定到剑道下拉列表

 @(Html.Kendo().DropDownListFor(a => a.MenuCategoryId)
                                .HtmlAttributes(new {style = "width:100%"})
                                .OptionLabel(new {
                                    name = "All",categoryId = 0})
                                .DataTextField("name")
                                .DataValueField("categoryId")
                                .DataSource(source =>
                                {
                                    source.Read(read =>
                                    {
                                        read.Action("GetlistofMenuCategory","MenuCategory");
                                    });
                                })
                                )

输出是空的 drodown...谁能帮我解决这个问题。

解决方法

请修改你的后端代码,正确的json应该是:

[{"categoryId":1,"name":"Momo"}]

结果:

enter image description here

我的后端测试代码:

public async Task<IActionResult> GetListOfMenuCategory()
{
    var model = new List<Model>()
    {
        new Model(){ categoryId=1,name="Momo"}
    };
    return Json(model);
}

更新:

如果不想改json,恐怕Kendo MVC DropDownList不支持这个。它总是需要来自服务器的 JSON 数组。可以通过 JavaScript 初始化 DropDownList 并使用模式数据选项来实现:

@Html.TextBoxFor(m => m.MenuCategoryId)
   
<script>
    $(function () {
        jQuery("#MenuCategoryId").kendoDropDownList({
            dataSource: {
                transport: {
                    read: {
                        url: "/MenuCategory/GetListOfMenuCategory"
                    }
                },schema: {
                    data: "data"     //the importance here
                },serverFiltering: true
            },dataTextField: "name",dataValueField: "categoryId",index: 0
        });
    });
</script>