【问题标题】:Kendo Grid - ASP MVC is not displaying the drop down listKendo Grid - ASP MVC 不显示下拉列表
【发布时间】:2017-03-08 10:24:44
【问题描述】:

我正在使用 ASP MVC 5、Kendo UI 和一些层开发一个项目,但我正在努力解决如何在 可编辑网格中显示 下拉列表 ,我按照这个例子:

Grid Editing / custom editor

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

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

Grid / ForeignKey column

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

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

dropdownlist in kendo grid not working

这是我的代码,在业务层中,我有这些类以便从数据库中返回类别:

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

最后,在视图中,我有这个剑道网格的代码:

@(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>

但是,它永远不会按应有的方式工作。有没有人遇到过这个问题?你是怎么做到的?感谢您的想法。

【问题讨论】:

    标签: asp.net-mvc kendo-ui kendo-grid kendo-asp.net-mvc kendo-dropdown


    【解决方案1】:

    对于 ForeignKey() 实现:

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

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

    对于“ClientTemplate”实现:

    如果您查看“网格编辑/自定义编辑器”示例的完整源代码(在随 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"])
    )
    

    【讨论】:

    • 感谢您的回答!我不知道 UIHint,它根本不在它的网页中,也许他们应该提供它或以某种方式解释它。我很确定它与不属于示例的 ProductViewModel 相关,我之前找不到它。感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多