繁体   English   中英

ASP.NET MVC中多个模型的相同视图

[英]Same view for multiple models in asp.net mvc

我有针对不同类别的几种模型,例如笔记本电脑,手机,软件,服装等。这些类别都有各自的属性。我有一个视图来显示类别列表,但有不同的操作方法,例如

public ActionResult Mobiles()
        {
            var q = from n in db.Mobiles
                    select n;
            return View(q);
        }
  public ActionResult Laptops()
        {
            var q = from n in db.Laptops
                    select n;
            return View(q);
       }

我应该针对不同的操作结果做出不同的观点还是只需要一个视图就可以呈现所有结果。

需要帮忙

如果要显示的属性在模型之间是公用的,例如categoryname则可以使用相同的View ,而不为其声明特定的Model

如果所有模型共享一个公共Interface并且只想显示在这些Interfaces上定义的属性,则可以在View中将Model声明为Interface

例如:

public Interface IProduct
{
    string Category {get;set;}
    string Name {get;set;}
}

public class Laptop : IProduct
{
    public string Category {get;set;}
    public string Name {get;set;}
    public bool HasBluRay {get;set;}
}

public class Mobile :IProduct
{
    public string Category {get;set;}
    public string Name {get;set;}
    public bool externalRAMSlot {get;set;}
}

现在,如果您只想列出产品的CategoryName ,则可以有以下视图:

@model IEnumerable<IProduct>
<table>
    <tr>
        <th>Category</th>
        <th>Product Name </th>
    </tr>
    @for(var product in Model)
    {
    <tr>
        <td>@product.Category</td>
        <td>@product.Name</td>
    </tr>
    }
</table>

您必须采用不同的视图来显示不同类别的详细信息,例如

笔记本电脑,手机,软件,服装等,因为您所说的型号不同

每个类别的类别,因此在MVC中的一个视图中,您可以采用一个模型类别

不同的视图将满足您的需求,否则您必须为所有类别创建一个viewmodel

视图中不可能有某种“通用视图模型”。 有哪些不同的属性?

如果它们几乎相同,则所有类别的视图模型都可以相同,并且视图中具有某种条件。 喜欢:

class =“ @(Model.IsLaptop?”东西“:”“)

另一种解决方案是在接口中具有通用属性,并对视图中的视图使用局部视图。 然后,您将不得不使用多个视图,但其中的标记最少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM