Asp.net mvc 对具有相似模型的控制器操作使用相同视图

Asp.net mvc 对具有相似模型的控制器操作使用相同视图,asp.net-mvc,asp.net-mvc-4,Asp.net Mvc,Asp.net Mvc 4,我有很多相同格式的模型(像下面的模型,只有Id和Name属性),它们都是从实体模型继承的 public abstract class Entity { public int Id { get; set; } } public class Exapmle1 : Entity { public string Name { get; set; } } public c

我有很多相同格式的模型(像下面的模型,只有Id和Name属性),它们都是从实体模型继承的

  public abstract class Entity 
        {
          public int Id { get; set; }
        }
     public class Exapmle1 : Entity
        {
             public string Name { get; set; }
        }
     public class Exapmle2 : Entity
        {
             public string Name { get; set; }
        }
     public class Exapmle3 : Entity
        {
             public string Name { get; set; }
        }
我不希望在CRUD操作中为每个模型实现多个控制器和对应视图。 有什么方法可以实现最低限度的实施吗??

例如,对于使用相同格式模型的所有已实现控制器,只有一个索引视图(列表)。

您可以使用具有接受实体(基类)的动态视图模型和控制器操作的视图。它可能看起来像这样

控制器:

public ActionResult Index(Entity foo)
{
    if(foo is Example1)
{
    var e1 = foo as Example1;
    //do your stuff
}

    return View();
}
视图:

@模型动态
@{
ViewBag.Title=“IndexNotStonglyTyped”;
}
索引类型不正确

@型号.名称
@Model.Id


当您拥有密切相关的实体组(或任何其他对象)时,一种可以很好地工作的方法是将它们拆分为可组合的接口,例如:

public interface IIdIdentity
{
    int Id { get; set; }
}

public interface INameIdentity
{
    int Name { get; set; }
}

public interface IYourGroup : IIdIdentity, INameIdentity
{

}

public class Exapmle1 : IYourGroup
{
    public int Id { get; set; }

    public int Name { get; set; }
}

然后您的视图可以接受任何类型的实体
IYourGroup
,只要您的域实体满足接口。

最后,我发现通用控制器和共享视图的组合是最好的方式。在这种情况下,每个控制器也可以分别进行身份验证

通用控制器:

 public abstract class GenericController<T> : Controller
        where T : BaseInformation
    {  //Controller Implementation for Index, Create, Edit, Delete   }
最终控制员

[Authorize(Roles = "Admin")]
      public class Base1Controller : GenericController<Base1>
        {
        }
[Authorize(Roles = "Helpdesk")]
        public class Base2Controller : GenericController<Base2>
        {
        }
[Authorize(Roles=“Admin”)]
公共类Base1Controller:GenericController
{
}
[授权(角色=“帮助热线”)]
公共类Base2Controller:GenericController
{
}
@model BaseInformation
//Model Implementation 
[Authorize(Roles = "Admin")]
      public class Base1Controller : GenericController<Base1>
        {
        }
[Authorize(Roles = "Helpdesk")]
        public class Base2Controller : GenericController<Base2>
        {
        }