我正在尝试使用 HTML 帮助器在 Kendo UI Grid 中设置下拉列表。
当我单击编辑网格时,会出现下拉菜单,我可以选择一个值。但是,当我单击更新时,这不会保存在数据库中(尽管简单的字符串 WordName 字段会保存)。
当您不编辑字段时,我还希望 WordViewModel 中的 CatId 值也显示为单词/下拉列表。
据我所知,我没有将 int CatId 链接到 GetCategories 列表的任何内容。我该如何连接这两者?我已经阅读了一些关于 column.ForeignKey 的内容,但我不明白。以下是我所有的相关代码。
我的 WordViewModel(从一个类似的、稍微复杂一点的数据库模型加载)
public class WordViewModel
{
public int WordId { get; set; }
[Required]
public string WordName { get; set; }
public Nullable<int> CatId { get; set; }
}
我的类别模型(由数据库生成)
public partial class Category
{
public Category()
{
this.Words = new HashSet<Word>();
}
public int CatId { get; set; }
public string CategoryName { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Word> Words { get; set; }
}
这是我在 Index.cshtml 中网格的剃须刀代码
@(Html.Kendo().Grid<WordViewModel>
()
.Name("wordGrid")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(word => word.WordId); // Specify the property which is the unique identifier of the model
model.Field(word => word.WordId).Editable(false); // Make the ID property not editable
})
.Read(read => read.Action("Read", "Words")) //Populate the grid with Words
.Update(update => update.Action("Update", "Words")) // Action invoked when the user saves an updated data item
)
.Editable(editable => editable.Mode(GridEditMode.InLine)) // Use inline editing mode
.Columns(columns =>
{
columns.Bound(c => c.WordName);
columns.Bound(c => c.CatId).EditorTemplateName("_CategoryDropdown"); //link to EditorTemplate with the same name
columns.Command(commands =>
{
commands.Edit(); // The "edit" command will edit and update data items
}).Title("Commands").Width(200);
})
.Filterable()
)
编辑器模板_CategoryDropdown.cshtml
@(
Html.Kendo().DropDownList()
.Name("Category") //is this Name important?
.DataTextField("CategoryName")
.DataValueField("CategoryId")
.DataSource(source =>
{
source.Read(read => { read.Action("GetCategories", "Words"); });
})
.OptionLabel("Select a category")
)
我从数据库中获取下拉列表的功能。
public JsonResult GetCategories()
{
var items = db.Categories.ToList().Select(c => new Category
{
CatId = c.CatId,
CategoryName = c.CategoryName
});
return Json(items, JsonRequestBehavior.AllowGet);
}