【发布时间】:2013-04-05 10:58:42
【问题描述】:
所以我的模型中有这个 Fee 抽象类(由 EF 生成,并考虑到数据库优先)
public abstract partial class Fee
{
public int FeeId { get; set; }
public int ProductId { get; set; }
public string Name { get; set; }
public decimal StandardPrice { get; set; }
}
它被许多其他类继承以模拟不同类型的费用,例如QuarterlyFee 之类的东西。我在模型中还有一个 Customer 类,客户可以有自定义费率,由 CustomerRate 类建模。
现在在客户详细信息页面上,我正在尝试显示客户的所有可能费用,以便用户可以选择哪些费率是自定义的,哪些是标准费率,没有投标交易我只是创建一个 ViewModel 类 PossibleFee 来建模:
public class PossibleFee
{
public int CustomerId { get; set; }
public int FeeId { get; set; }
public Boolean CustomRate { get; set; }
public decimal CustomerPrice { get; set; }
public virtual Customer Customer { get; set; }
public virtual Fee Fee { get; set; }
}
我在 Customer 类中添加了一个属性来保存可能的费用 (ICollection PossibleFees),我在 Controller 方法中填充了该属性 (public ActionResult Details(int id = 0)),稍后是一个 EditorTemplate,然后我'根据用户可以编辑的产品,客户可能需要支付的所有费用列表。
但是现在在回发时,当我点击保存按钮时,默认模型绑定器会完成其工作并尝试填充可能费用的 ICollection,并为每个可能费用尝试创建一个费用对象以填充同名的属性。
当然它不起作用,因为 Fee 是抽象的,问题很简单:我如何告诉 DefaultModelBinder 在回发时忽略该属性,因为我在回发时不需要它?
我知道我可以简单地将我需要的字段复制到可能费用类的可能费用的 EditorTenplate 上,甚至可以从费用中删除摘要。但我想知道是否可以在不接触模型的情况下根据需要调整 DefaultModelBinder。
编辑 2: 在我看来,Yarx 提供了一个更清洁的解决方案,请参阅下面的 2 个帖子
编辑: 好吧,Carlos Corral Carvajal 几乎是正确的,在 ModelBinder 尝试创建对象后调用了 SetProperty 方法,所以我不得不改写 BindProperty
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Attributes.Contains(new ModelBinderIgnoreOnPostback()))
{
return;
}
base.BindProperty(controllerContext, bindingContext,propertyDescriptor);
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=false)]
public class ModelBinderIgnoreOnPostback : Attribute {}
添加了自定义属性以防有人需要它
【问题讨论】:
-
我发现始终拥有视图模型更容易。序列化为 json 更容易,并使视图独立于 db 表。
标签: asp.net-mvc abstract-class defaultmodelbinder