ASP.NET MVC通用控制器

11
我考虑在ASP.NET MVC中实现一个通用控制器。
PlatformObjectController<T>

T是一个(生成的)平台对象。

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

例如,一个相关的问题是结果URL是什么样子的。


你需要为每个 T 配置路由...或者在运行时执行一些查找操作。这样做会有性能方面的影响,但除此之外,它似乎是一个不错的想法。 - bzlm
1个回答

19

没错,你只是不能直接使用它,但可以继承它并使用子级元素。

这里是我使用的一个:

     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


好的 - 所以我的问题是可以解决的。 如果为类型参数生成类型,并通用实现基本控制器,我所需要做的就是为我想要用作类型参数的每个类型生成派生控制器。这就是最简单的方法。 酷! - Frank Michael Kraft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接