【问题标题】:How to display an object which doesn't belong to my model?如何显示不属于我的模型的对象?
【发布时间】:2014-05-19 15:52:31
【问题描述】:

我正在用 ASP MVC 4 做一个 Web 项目。
我有一个强类型(model :Product) 视图 (ProductIndex.cshtml),我想在此视图中显示所有商家的列表。

最好的方法是什么?
- 在我的产品类 (Icollection) 中创建一个新属性?
我不太喜欢这种方法,因为产品不应该有商家列表...

- 创建一个部分视图类型(IEnumerable)并从我的 ProductIndex 视图中调用它,并使用 ViewData 对象作为参数?
我不确定我是否能够使用这种方法在列表框中显示模型(IEnumerable)...我想我只能使用属性而不是模型填充列表框...
请告诉我!

谢谢

public class Product
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int MerchandID { get; set; }


    }

 public class ProductViewModel
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int MerchandID { get; set; }

        public  ICollection<Merchant> Lesmarchands { get; set; }
    }

【问题讨论】:

    标签: html asp.net-mvc razor view listbox


    【解决方案1】:
    public class ProductViewModel
    {
        public Product Product {get;set;}
        public List<Merchant> Merchants {get;set;}
    }
    

    【讨论】:

    • 我的代码有一个错误,因为实体需要在视图模型类中有一个 ID 属性,所以我将在这个类中复制我的产品对象的所有属性而不是产品属性。
    • 不要那样做。使用 Product.ID,在客户端,html 元素的名称应该是
    • 我无法基于此 Viewmodel 创建新视图。我收到错误消息:ProductviewModel:EntityType'ProductViewModel' has no key defined.Define the key for this entitytype.ProductViewModels:EntityType: entitySet 'ProductviewModels' 基于没有定义键的类型 'ProductviewModel'。我不明白这个实体“ProductviewmodelS”是如何以及为什么被创建的?
    • 您的产品有 PK 吗?你能展示你的产品模型吗?
    • 是的,还有一个 FK MerchantID。
    【解决方案2】:

    我认为拥有与您的产品视图模型相关联的商家列表并没有什么坏处。 特别是如果两者都需要满足您的视图需求。我倾向于在我的模型之上创建视图模型,作为实际领域模型之上的抽象。

    当然,稍微不同的方法是通过 Ajax 加载商家,然后将它们与模型中的产品断开连接。

    【讨论】:

    • 不,我会说在产品模型中拥有商家列表是个坏主意...但我没想过要创建 VIEW 模型产品...我使用 Product 模型作为查看模型...我猜这不是最好的主意
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2021-08-01
    相关资源
    最近更新 更多