同一个视图在asp.net mvc中的多个模型

本文关键字:模型 mvc 视图 asp net 同一个 | 更新日期: 2023-09-27 18:17:14

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

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);
       }

我应该为不同的操作结果制作不同的视图还是只需要一个视图来呈现所有。

需要帮助的

同一个视图在asp.net mvc中的多个模型

如果您想要显示的属性在您的模型之间是通用的,如categoryname,那么您可以使用相同的View,而不为它声明特定的Model

如果你所有的模型共享一个共同的Interface,你只想显示那些Interfaces上定义的属性,那么你可以在你的View中声明你的ModelInterface

例如:

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 = " @(模型。IsLaptop吗?"something": ")

另一种解决方案可能是在一个界面中使用公共属性,并在视图中使用部分视图。然后,您将不得不使用几个视图,但其中的标记最少。