Fra*_*aft 12 generics asp.net-mvc controller
我正在考虑在ASP.NET MVC中实现一个通用的Controller.
PlatformObjectController<T>
Run Code Online (Sandbox Code Playgroud)
其中T是(生成的)平台对象.
这可能吗?有经验/文件吗?
例如,一个相关问题是生成的URL是如何生成的.
Omu*_*Omu 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");
}
}
Run Code Online (Sandbox Code Playgroud)
和用法:
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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
代码在这里:http: //code.google.com/p/asms-md/source/browse/trunk/WebUI/Controllers/FieldController.cs
更新:
现在使用这种方法:http://prodinner.codeplex.com