如何在模型绑定过程中设置模型属性?

时间:2010-07-08 01:58:34

标签: asp.net-mvc-2

我的许多模型对象都从一个名为AuditedEntity的类继承,该类跟踪对象的更改。我希望继承自AuditedEntity的模型对象在模型绑定过程中构造时自动填充相应的字段。我一直在寻找对默认模型绑定器进行子类化,但没有太多运气。

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:3)

这些属性是使用已知值填充的,还是来自良好来源的值。或者这些属性是否使用依赖于表单/路由/查询等的值的值填充?

对DefaultModelBinder进行子类化应该没问题,例如:

public class MyModel
{
  public string Forename { get; set }

  public string SomeSpecialProperty { get; set; }
}

public MyModelBinder : DefaultModelBinder
{
  public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
    var model = (MyModel)base.BindModel(controllerContext, bindingContext);

    model.SomeSpecialProperty = // Do something here...

    return model;
  }
}

ModelBinder.Binders[typeof(MyModel)] = new MyModelBinder();

到目前为止你发现了什么?

答案 1 :(得分:0)

我最终不得不依赖所有绑定的数据。这是我最终使用的解决方案。将代码放在OnModelUpdated中允许我依赖已经设置的其他属性。

public class AuditedEntityModelBinder : DefaultModelBinder
{

    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType.IsSubclassOfGeneric(typeof(AuditedEntity<>)))
        {
            string name = controllerContext.HttpContext.User.Identity.Name;

            if(!name.IsNullOrEmpty())
            {
                if((bool) bindingContext.ModelType.GetProperty("IsNew").GetValue(bindingContext.Model, null))
                {
                    bindingContext.ModelType.GetProperty("CreatedBy").SetValue(bindingContext.Model, name, null);
                    bindingContext.ModelType.GetProperty("Created").SetValue(bindingContext.Model, DateTime.Now, null);
                }
                else
                {
                    bindingContext.ModelType.GetProperty("ModifiedBy").SetValue(bindingContext.Model, name, null);
                    bindingContext.ModelType.GetProperty("Modified").SetValue(bindingContext.Model, DateTime.Now, null);
                }

            } 
        }

        base.OnModelUpdated(controllerContext, bindingContext);
    }
}
相关问题