通过下拉列表引用另一个实体的实体编辑表单

时间:2010-10-05 06:51:02

标签: asp.net-mvc nhibernate asp.net-mvc-2

我的问题涉及通过编辑表单更新实体,并引用由下拉列表表示的另一个实体。我正在使用ASP.NET MVC 2.详细信息:

Public Class Category
{
   int Id { get; set;}
   string Name { get; set}
   Category Parent { get; set}
}
  • EditorFor
  • 生成的类别的编辑页面
  • “编辑”页面包含一个下拉列表,用于选择父类别,名称/ id = Parent.Id
  • 下拉列表中有value=''的“无”条目(对于没有父级的类别)。

动作中的更新流程:

  • 通过ID从存储库检索的当前实体。
  • TryUpdateModel应用于检索到的实体

问题:

当提交已编辑的类别时,如果下拉列表设置为“none”,则当它尝试在parent.id上更新时,正在为“父”实例化新实体。当通过ORM持久化时,这会导致问题。 那么,在这种情况下该怎么办?有没有办法阻止'父'对象被实例化,并将父引用保留为空?

感谢。

更新: 我正在使用NHibernate作为我的ORM,以防这是有用的。

2 个答案:

答案 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"}