具有可编辑枚举列的 Kendo MVC 网格 [英] Kendo MVC grid with editable enum column
问题描述
我有一个简单的模型,需要在 Kendo 的 MVC Grid 组件中显示和编辑.
I have a simple model that I need to display and edit in Kendo's MVC Grid component.
public class MyModel
{
public int Id {get; set;}
public string SomeProperty {get; set;}
public MyEnum MyEnum {get; set;}
}
public enum MyEnum
{
FirstItem = 1,
SecondItem = 2,
ThirdItem = 3
}
我的网格设置如下:
@(Html.Kendo()
.Grid<MyModel>()
.Name("grid").Columns(columns =>
{
columns.Bound(o => o.SomeProperty).Width(200);
columns.Bound(o => o.MyEnum).Width(200);
columns.Command(command =>
{
command.Edit().Text("Edit");
}).Width(220);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(false)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.SomeProperty);
model.Field(p => p.MyEnum);
})
.Create(...) // removed for confidentiality
.Read(...)
.Update(...)
.Events(...)
).Filterable()
.Sortable())
执行编辑命令后,我在Update(...)
中定义的控制器方法中收到更新的模型.
After executing the edit command, I receive updated model in controller's method defined in Update(...)
.
public virtual async Task<ActionResult> Update(
[DataSourceRequest] DataSourceRequest request,
MyModel myModel)
但是无论我做什么,控制器中的 myModel
的默认值都是 MyEnum
.即使我只将 MyEnum
设置为 SecondItem
的项目的 SomeProperty
更改为控制器中的 FirstItem
.这是通过查看 POST 请求来验证的,因此问题出在网格中的某个地方,而不是服务器上.
However no matter what I do, myModel
in controller has default value of MyEnum
. Even if I change just SomeProperty
of item that has MyEnum
set to SecondItem
, it will be FirstItem
in the controller. This was verified by looking at the POST request, so the problem is somewhere in the Grid, not on server.
如何进行正确的数据绑定以确保 Kendo 发送正确的 MyEnum
值?
How to do proper data binding to ensure Kendo sends correct MyEnum
values?
推荐答案
你需要在列上使用 .ForeignKey()
而不是绑定:
You need to use .ForeignKey()
on a column instead of binding:
@(Html.Kendo()
.Grid<MyModel>()
.Name("grid").Columns(columns =>
{
columns.ForeignKey(o => o.MyEnum, ).EditorTemplateName("GridForeignKey").Width(200);
// SNIP
然后像这样在Views/Shared/EditorTemplate
中定义GridForeignKey.cshtml
:
@model object
@{
var selectList = (SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"];
}
@Html.DropDownListFor(m => m, selectList, "Choose...")
通过这种方式,您可以在网格中获得一个下拉列表,并在 POST 时将正确的值输入到您的控制器中.
This way you get a dropdown in your grid and will get correct values into your controller on POST.
这篇关于具有可编辑枚举列的 Kendo MVC 网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!