asp.net-mvc - asp.net mvc 通用 Controller

标签 asp.net-mvc controller generics

我正在考虑在 ASP.NET MVC 中实现通用 Controller 。

PlatformObjectController<T>

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

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

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

最佳答案

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

这是我使用的一个:

     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

关于asp.net-mvc - asp.net mvc 通用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413626/

相关文章:

generics - 具有依赖于接收器类型参数的泛型类型的 Kotlin 扩展函数(未明确指定)

Swift 4.1 - Set 扩展要求 Element 符合 Encodable

c# - NewtonSoft Json DeserializeObject 空 Guid 字段

sql - LINQ-to-SQL 存储库模式尝试有效,但担心分离

controller - 从网址获取路线

javascript - 单击按钮时 $state.go() 不会第一次调用 Controller

c# - 具有 [Authorize] 的环境相关 Controller

c# - 将 Html.DropDownList 助手与 ViewBag 列表一起使用

javascript - json 和 Utc 日期时间

java - 具有泛型参数和返回类型的泛型方法