Asp.net mvc 使用自定义编辑器绑定网格子模型
我有一个带有自定义编辑器的可编辑剑道UI网格。每当我尝试在自定义编辑器中的文本框外单击时(即Kendo在网格模型中设置值时),我都会收到如下javascript错误:Asp.net mvc 使用自定义编辑器绑定网格子模型,asp.net-mvc,kendo-ui,kendo-grid,Asp.net Mvc,Kendo Ui,Kendo Grid,我有一个带有自定义编辑器的可编辑剑道UI网格。每当我尝试在自定义编辑器中的文本框外单击时(即Kendo在网格模型中设置值时),我都会收到如下javascript错误: 0x800a138f-JavaScript运行时错误:无法设置未定义或空引用的属性“PercentWeight” 在调试器中,异常发生在: function anonymous(d,value) { d.PercentInfo.PercentWeight=value } 当我将鼠标悬停在d上时,它具有除PercentIn
0x800a138f-JavaScript运行时错误:无法设置未定义或空引用的属性“PercentWeight”
在调试器中,异常发生在:
function anonymous(d,value) {
d.PercentInfo.PercentWeight=value
}
当我将鼠标悬停在d
上时,它具有除PercentInfo
之外的所有InCreditViewModel
属性,当我将鼠标悬停在PercentInfo
上时,它是未定义的
这是我的网格模型:
public class IngredientViewModel {
public string EncryptedIngredientId { get; set; }
public string CasNumber { get; set; }
public string IngredientName { get; set; }
[UIHint("PercentWeightEditor")]
public PercentInfoViewModel PercentInfo { get; set; }
}
以下是InCreditViewModel
中使用的PercentInfoViewModel
模型:
public class PercentInfoViewModel {
public decimal? PercentWeight { get; set; }
public string PercentUnit { get; set; }
}
以下是部分网格的.cshtml:
@(Html.Kendo().Grid<IngredientViewModel>(Model)
.Name("IngredientsGrid")
.Editable(editable => editable.Mode(GridEditMode.InLine).Enabled(true))
.BindTo(Model)
.DataSource(ds => ds
.Ajax()
.ServerOperation(false)
.Events(ev => ev.Error("onGridError"))
.Model(m => {
m.Id(p => p.EncryptedIngredientId);
m.Field(p => p.EncryptedIngredientId).Editable(false);
m.Field(p => p.PercentInfo);
})
.Read("IngGrid_Read", "Company")
.Update("IngGrid_Update", "Company")
.Create("IngGrid_Create", "Company")
.Destroy("IngGrid_Destroy", "Company"))
.ToolBar(tbar => tbar.Create())
.Columns(c => {
c.Bound(m => m.CasNumber);
c.Bound(m => m.IngredientName);
c.Bound(m => m.PercentInfo).ClientTemplate("#= PercentInfo.PercentWeight # #= PercentInfo.PercentUnit #");
c.Command(command => {
command.Edit();
command.Destroy();
}).Width(200);
})
)
我做错了什么?我不得不修改网格设置的Model
调用,将空模型作为默认值。下面是新的代码:
.Model(m => {
m.Id(p => p.EncryptedIngredientId);
m.Field(p => p.EncryptedIngredientId).Editable(false);
m.Field(p => p.PercentInfo)
/* I added this line --> */ .DefaultValue(new PercentInfoViewModel());
})
通过这种方式,自定义编辑器始终可以向空模型分配属性,而不是尝试将属性分配给不存在的对象(这是导致异常的原因)
.Model(m => {
m.Id(p => p.EncryptedIngredientId);
m.Field(p => p.EncryptedIngredientId).Editable(false);
m.Field(p => p.PercentInfo)
/* I added this line --> */ .DefaultValue(new PercentInfoViewModel());
})