【问题标题】:asp.net mvc generic controllerasp.net mvc 通用控制器
【发布时间】:2010-08-05 10:01:13
【问题描述】:

我正在考虑在 ASP.NET MVC 中实现一个通用控制器。

PlatformObjectController<T>

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

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

例如,一个相关的问题是生成的 URL 是怎样的。

【问题讨论】:

  • 您必须为每个 T... 配置路由或在运行时执行一些查找魔法。这对性能有影响,但除此之外,这似乎是个好主意。

标签: asp.net-mvc controller generics


【解决方案1】:

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

这是我使用的一个:

     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

【讨论】:

  • 好的 - 所以我的问题是可以解决的。如果生成了类型参数的类型,并且一般实现了基本控制器,那么我需要做的就是为我想用作类型参数的每种类型生成派生控制器。这很简单。酷!
猜你喜欢
  • 2011-02-21
  • 2023-04-05
  • 2010-12-17
  • 2010-12-21
  • 2017-05-08
  • 2011-01-09
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多