2010-08-05 161 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