我的问题涉及通过编辑表单更新实体,并引用由下拉列表表示的另一个实体。我正在使用ASP.NET MVC 2.详细信息:
Public Class Category
{
int Id { get; set;}
string Name { get; set}
Category Parent { get; set}
}
EditorFor
Parent.Id
value=''
的“无”条目(对于没有父级的类别)。动作中的更新流程:
问题:
当提交已编辑的类别时,如果下拉列表设置为“none”,则当它尝试在parent.id上更新时,正在为“父”实例化新实体。当通过ORM持久化时,这会导致问题。 那么,在这种情况下该怎么办?有没有办法阻止'父'对象被实例化,并将父引用保留为空?
感谢。
更新: 我正在使用NHibernate作为我的ORM,以防这是有用的。
答案 0 :(得分:2)
对于自定义模型绑定器来说,这看起来很不错:
public class CategoryModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = base.BindModel(controllerContext, bindingContext) as Category;
if (model != null && model.Id == null) // adapt this test if necessary
{
return null;
}
return model;
}
}
在Application_Start
:
ModelBinders.Binders.Add(typeof(Category), new CategoryModelBinder());
还要确保模型上的Id
属性是可以为空的整数,否则如果您尝试将其绑定到空字符串,则绑定程序将崩溃。
答案 1 :(得分:0)
您可以将 parentId 参数添加到操作方法并手动进行检查,如果它为null,则调用带有excludeProperties设置为
的TryUpdateModel方法new [] {"Parent"}