2010-08-05 131 views
12

我想在ASP.NET MVC中实现一个通用控制器。asp.net mvc通用控制器

PlatformObjectController<T> 

其中T是(生成的)平台对象。

这可能吗?有经验/文档吗?

例如,一个相关问题是结果URL的结果。

+0

你将不得不进行路由配置每个'T' ......或在运行时执行一些查找魔术。这对性能有影响,但除此之外,它似乎是个好主意。 – bzlm 2010-08-06 08:01:31

回答

18

是这个原因,你不能直接使用它,但你可以继承它,并用孩子的

这里是一个我用:

 public class Cruder<TEntity, TInput> : Controller 
     where TInput : new() 
     where TEntity : new() 
    { 
     protected readonly IRepo<TEntity> repo; 
     private readonly IBuilder<TEntity, TInput> builder; 


     public Cruder(IRepo<TEntity> repo, IBuilder<TEntity, TInput> builder) 
     { 
      this.repo = repo; 
      this.builder = builder; 
     } 

     public virtual ActionResult Index(int? page) 
     { 
      return View(repo.GetPageable(page ?? 1, 5)); 
     } 

     public ActionResult Create() 
     { 
      return View(builder.BuildInput(new TEntity())); 
     } 

     [HttpPost] 
     public ActionResult Create(TInput o) 
     { 
      if (!ModelState.IsValid) 
       return View(o); 
      repo.Insert(builder.BuilEntity(o)); 
      return RedirectToAction("index"); 
     } 
    } 

和用法:

public class FieldController : Cruder<Field,FieldInput> 
    { 
     public FieldController(IRepo<Field> repo, IBuilder<Field, FieldInput> builder) 
      : base(repo, builder) 
     { 
     } 
    } 

    public class MeasureController : Cruder<Measure, MeasureInput> 
    { 
     public MeasureController(IRepo<Measure> repo, IBuilder<Measure, MeasureInput> builder) : base(repo, builder) 
     { 
     } 
    } 

    public class DistrictController : Cruder<District, DistrictInput> 
    { 
     public DistrictController(IRepo<District> repo, IBuilder<District, DistrictInput> builder) : base(repo, builder) 
     { 
     } 
    } 

    public class PerfecterController : Cruder<Perfecter, PerfecterInput> 
    { 
     public PerfecterController(IRepo<Perfecter> repo, IBuilder<Perfecter, PerfecterInput> builder) : base(repo, builder) 
     { 
     } 
    } 

的代码是在这里: http://code.google.com/p/asms-md/source/browse/trunk/WebUI/Controllers/FieldController.cs

更新:

这里使用这种方法现在:http://prodinner.codeplex.com

+0

好的 - 所以我的问题是可以解决的。 如果生成了类型参数的类型,并且基本控制器是一般实现的,那么我需要做的就是为每个类型生成派生控制器,并将其用作类型参数。这很简单。 酷! – 2010-08-09 11:04:30