在我的项目中,每个domainmodel都有一个viewmodel,并在多个视图中重用这个viewmodel。
一个视图模型的示例
public class ProductViewModel
{
public int ProductId { get; set; }
public int ProductGroupId { get; set; }
public bool IsLinkedToErp { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Standard")]
public bool IsDefault { get; set; }
[MaxLength(50)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Artnr")]
public string ArtNo { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Beskrivning")]
public string Description { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Specifikation")]
public string Specification { get; set; }
[MaxLength(5)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Enhet")]
public string Unit { get; set; }
[MaxLength(4)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Konto")]
public string Account { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Netto")]
public decimal NetPrice { get; set; }
public string ChUser { get; set; }
public DateTime ChTime { get; set; }
public string GetUpdatedDate
{
get { return String.Format("{0:d}", ChTime); }
}
public string GetNetPrice
{
get { return String.Format("{0:0.00}", NetPrice); }
}
}
我在ProductController中的所有视图都重用了这个ViewModel。 对于列表,添加和编辑。但在列表中我只使用了一些属性。
然后我使用Automapper映射到域,反之亦然。
现在我想知道是否有人有这方面的经验。你认为随着项目的发展,我会在使用这个解决方案时遇到问题吗?
答案 0 :(得分:3)
我会考虑拆分ListViewModel和Add / Edit视图模型,只是因为您可能正在填充并发送比您真正需要的更多数据。
通过利用继承,您可以快速创建两个只包含视图所需数据的类。根据您的示例,我会考虑以下内容:
public class ProductListViewModel{
public IEnumerable<ProductListModel> products {get;set;}
public string SomeOtherPotentialVariableForProductList {get;set;}
}
public class ProductListModel{
public int ProductId { get; set; }
public int ProductGroupId { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Beskrivning")]
public string Description { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Netto")]
public decimal NetPrice { get; set; }
}
public class ProductViewModel : ProductListModel
{
public bool IsLinkedToErp { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Standard")]
public bool IsDefault { get; set; }
[MaxLength(50)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Artnr")]
public string ArtNo { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Specifikation")]
public string Specification { get; set; }
[MaxLength(5)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Enhet")]
public string Unit { get; set; }
[MaxLength(4)]
[Required(AllowEmptyStrings = false)]
[Display(Name = "Konto")]
public string Account { get; set; }
public string ChUser { get; set; }
public DateTime ChTime { get; set; }
public string GetUpdatedDate
{
get { return String.Format("{0:d}", ChTime); }
}
这完成了一些事情。