Reputation: 994
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
}
And I have my grid set up like this:
@(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())
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)
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.
How to do proper data binding to ensure Kendo sends correct MyEnum
values?
Upvotes: 2
Views: 4872
Reputation: 35116
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
and then define GridForeignKey.cshtml
in Views/Shared/EditorTemplate
like this:
@model object
@{
var selectList = (SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"];
}
@Html.DropDownListFor(m => m, selectList, "Choose...")
This way you get a dropdown in your grid and will get correct values into your controller on POST.
Upvotes: 1
Reputation: 931
I had the same problem. You should to use EditorTemplate (MyEnum.cshtml in Shared\EditorTemplates folder) for MyEnum property:
@model MyEnum
@(Html.Kendo().DropDownListFor(m => m)
.Name("MyEnum")
.BindTo(EnumHelper.GetSelectList(Model.GetType()))
.OptionLabel("Please select MyEnum"))
Upvotes: 3
Reputation: 874
There may be a conflict in your model since your enum object property matches the type. Suggest you rename it something like this and give it a try;
public class MyModel
{
public int Id {get; set;}
public string SomeProperty {get; set;}
public MyEnum EnumProperty {get; set;}
}
Upvotes: 0