Kendo Grid - ASP MVC没有显示下拉列表

时间:2017-03-08 10:24:44

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

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

Grid Editing / custom editor

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

example

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

Grid / ForeignKey column

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

Example 2

此外,我在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图层中,控制器会使用以下某些方法填充视图:

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

最后,在视图中,我有Kendo Grid的代码:

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

然而,它永远不会像它应该的那样工作。有没有人遇到这个问题?你是如何管理它的?谢谢你的想法。

1 个答案:

答案 0 :(得分:3)

对于ForeignKey()实现:

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

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

对于&#34; ClientTemplate&#34;实现:

如果您看一下&#34;网格编辑/自定义编辑器的完整源代码&#34;示例(在使用Kendo MVC安装的示例中),使用模型上的UIHint指定EditorTemplate。 即(使用你的类名)

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"])
)
相关问题