Kendo 网格 - ASP MVC 未显示下拉列表

Kendo Grid - ASP MVC is not displaying the drop down list

我正在使用 ASP MVC 5、Kendo UI 和一些层开发一个项目,但我正在为如何显示 而苦恼可编辑网格内的下拉列表,我遵循了这个例子:

Grid Editing / custom editor

但是,我遇到了严重的问题,因为下拉列表从未 出现 ,它显示了两个文本框。

此外,如果我 运行 外键列 示例:

Grid / ForeignKey column

我有一个不同的数字上下的结果:

此外,我从 Whosebug 测试了这个例子,结果是两个文本框或数字上下(这取决于我是绑定列还是使用外键列):

dropdownlist in kendo grid not working

这是我的代码,在 业务层 中,我有这些 类 以便 return 来自数据库的类别:

using Test.DB.Operations;
using System.Collections.Generic;
using System.Linq;

namespace Test.Business
{
    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

    public class CategoryData
    {
        public static List<Category> GetCategories()
        {
            var catData = DatabaseService.GetEntities<DB.Category>().ToList();

            return (from cData in catData select new Category() { ID = cData.ID, Name = cData.Name }).ToList();
        }
    }
}

稍后,在我的 MVC 层 中,Controller 使用如下方法填充视图:

using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Test.Business;
using Test.Classes;
using Test.MVC.Classes;
using Test.MVC.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Test.MVC.Controllers
{
    public class OrganizationDetailsController : Controller
    {
        public ActionResult Index(string ID)
        {
            PopulateCategories();

            if (!string.IsNullOrEmpty(ID))
            {
                var model = new OrganizationsModel();
                try
                {
                    model.hasError = false;
                    model.messageBox = null;
                }
                catch (Exception ex)
                {
                    model.hasError = true;
                    model.messageBox = new Tuple<string, string>("Error", "Please report it to the team");
                }
                return View(model);
            }
            else
            {
                return View();
            }
        }    

        public ActionResult OrganizationDetails_Read([DataSourceRequest]DataSourceRequest request, string ID)
        {
            try
            {
                var data = OrganizationDetailsData.GetOrganizationDetails(ID);
                DataSourceResult result = data.ToDataSourceResult(request);
                return Json(result);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult OrganizationDetails_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]<OrganizationDetails> oDetails)
        {
            return null;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult OrganizationDetails_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<OrganizationDetails> oDetails)
        {
            return null;
        }

        private void PopulateCategories()
        {
            var dataContext = CategoryData.GetCategories();

            ViewData["categories"] = dataContext;
            ViewData["defaultCategory"] = dataContext[0];
        }
    }
}

模型 看起来像这样:

using Test.Business;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Test.MVC.Models
{
    public class OrganizationsModel
    {
        public Tuple<string, string> messageBox;
        public bool hasError;
    }
}

最后,在 View 中,我有 Kendo 网格的代码:

@(Html.Kendo().Grid<Test.Business.OrganizationDetails>()
    .Name("gridDetails")
    .Columns(columns =>
    {
        columns.Bound(b => b.Name);
        columns.Bound(b => b.NumberOfEmployees);
        //columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "ID", "Name").Title("Categories").EditorTemplateName("dropdownTemplate");
        columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
        columns.Bound(p => p.Telephone);
        columns.Bound(p => p.Address);
    })
    .ToolBar(toolBar =>
    {
        toolBar.Create();
        toolBar.Save();
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Pageable()
    .Sortable()
    .Scrollable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.ID);
            model.Field(p => p.ID).Editable(false);
            model.Field(p => p.Category).DefaultValue(ViewData["defaultCategory"] as Test.Business.Category);
        })
        .PageSize(20)
        .Read(read => read.Action("OrganizationDetails_Read", "OrganizationDetails").Data("LoadParams"))
        .Create(create => create.Action("OrganizationDetails_Create", "Grid"))
        .Update(update => update.Action("Organization_Update", "Grid"))
    )
    .Resizable(resize => resize.Columns(true))
    .Reorderable(reorder => reorder.Columns(true))
)

<input type="hidden" id="orgID" value="1" />

<script id="dropdownTemplate" type="text/x-kendo-template">
    @(Html.Kendo().DropDownListFor(m => m)
        .Name("myDropDown")
        .DataValueField("ID")
        .DataTextField("Name")
        .BindTo((System.Collections.IEnumerable)ViewData["categories"])
    )
</script>

<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }

    function LoadParams() {
        var id = $("#orgID").val();
        return { ID: id }
    }
</script>

但是,它永远无法正常工作。有没有人遇到过这个问题?你是如何做到的?谢谢你的想法。

对于 ForeignKey() 实现:

您必须将 "dropdownTemplate" 放入 Views/Shared/EditorTemplates 的 cshtml 文件中。你不能使用 x-kendo-template 因为你没有使用 javascript 初始化......你正在使用剃须刀助手。您可能发生的情况是,您指定了一个不存在的 EditorTemplate(Shared/EditorTemplates 中没有 cshtml),因此它会中断。

或者,您可以完全不使用 EditorTemplateName(),Kendo 将自动使用 Views/Shared/EditorTemplates/GridForeignKey.cshtml 中的 EditorTemplate。

对于 "ClientTemplate" 实施:

如果您查看 "Grid Editing / custom editor" 示例的完整源代码(在随 Kendo MVC 安装的示例中),EditorTemplate 是使用模型上的 UIHint 指定的。 即(使用你的类名)

public class OrganizationDetails
{
    ...

   [UIHint("ClientCategory")]
    public CategoryViewModel Category {get; set;}
}

然后 Views/Shared/EditorTemplates 中必须有一个 ClientCategory.cshtml 文件,其中包含用于您的编辑器实现的剃刀。

在 Kendo 示例中,ClientCategory.cshtml 包含:

@model Kendo.Mvc.Examples.Models.CategoryViewModel

@(Html.Kendo().DropDownListFor(m => m)
    .DataValueField("CategoryID")
    .DataTextField("CategoryName")
    .BindTo((System.Collections.IEnumerable)ViewData["categories"])
)