asp.net mvc 通用控制器 [英] asp.net mvc generic controller

查看:33
本文介绍了asp.net mvc 通用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am thinking of implementing a generic Controller in ASP.NET MVC.

PlatformObjectController<T>

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

where T is a (generated) platform object.

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

Is this possible? Is there experience / documentation?

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

One related question for example is how the resulting URLs are.

推荐答案

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

yes it is, you just can't use it directly but you can inherit it and use the childs

这是我使用的一个:

     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

using this approach here now: http://prodinner.codeplex.com

这篇关于asp.net mvc 通用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆