C# 型号';要查看的依赖项数据

C# 型号';要查看的依赖项数据,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我有3个相关模型和我的项目 public class EditPaymentMethodModel { public PaymentMethodViewData PaymentViewData { get; set; } public BillingAddressModel BillingAddresses { get; set; } public CspacModel NewBillingAddress { get; set; } } public class Pay

我有3个相关模型和我的项目

public class EditPaymentMethodModel
{
    public PaymentMethodViewData PaymentViewData { get; set; }
    public BillingAddressModel BillingAddresses { get; set; }
    public CspacModel NewBillingAddress { get; set; }
}

public class PaymentMethodViewData 
{
    public int? PaymentMethodId { get; set; }
}

public class CreditCardViewData : PaymentMethodViewData
{
     public string CardNumber { get; set; }
     ....
     ....
     ....
     [ViagogoCpfCnpj(CardNoProperty = "CardNumber")]
     public string CpfOrCnpj { get; set; }
}
  • PaymentMethodViewData是所有付款方式的父项
  • CreditCardViewData由PaymentMethodViewModel继承
  • EditPaymentMethodModel是我的视图模型
  • PaymentMethodViewData实际上没有任何CreditCardViewData,但是我们有PaymentMethodHandler,它正在此行之后将CreditCardViewData添加到PaymentMethodViewData

    var paymentMethodViewData = PaymentMethodHandler.GetPaymentMethodData(payment, userId);
    
    最后我有一个视图,它的模型是EditPaymentMethodModel

    @model Viagogo.Mvc.OM.Pipeline.BuyPipeline.EditPaymentMethodModel
    
    我想做的是,如果支付类型是信用卡,我只想做下面的一行,但目前它给出了一个错误,我无法找出它

    @Html.TextBoxFor(m => m.PaymentViewData.CreditCardViewData.CpfOrCnpj)
    

    编辑1:运行时出错

    如果无法将
    public PaymentMethodViewData PaymentViewData{get;set;}
    更改为
    public CreditCardViewData PaymentViewData{get;set;}
    ,则可以向视图模型添加其他属性,如

    public class EditPaymentMethodModel
    {
      ....
      [ViagogoCpfCnpj(CardNoProperty = "CardNumber")]
      public string CpfOrCnpj
      {
        get
        {
          if (PaymentViewData != null && PaymentViewData is CreditCardViewData)
          {
            return ((CreditCardViewData)PaymentViewData).CpfOrCnpj;
          }
          return null;
        }
      }
    }
    
    您可以在视图中使用

    @Html.TextBoxFor(m => m.PaymentViewData.CreditCardViewData.CpfOrCnpj)
    

    但是,此属性没有setter,因此ModelBinder不会为
    CpfOrCnpj
    设置任何值。如果您在post方法中需要此值,则需要从
    FormCollection

    获取此值。给我5分钟,我有5分钟的缓存时间来构建项目@Exception是您的付款方法处理程序将属性
    PaymentViewData
    设置为
    CreditCardViewData
    ?@StephenMuecke是的,但问题是,我对依赖注入一无所知。虽然我在PaymentMethodViewData上没有creditcardviewdata属性,但它可以设置为默认值,修改视图模型是最好的。你为什么不能那样做?如果没有,我可以发布一个答案,但有点ugly@StephenMuecke原因是我不知道怎么做。