我怎么能继承一个ASP.NET MVC控制器和仅改变看法? [英] How can I inherit an ASP.NET MVC controller and change only the view?
问题描述
我有一个控制器的从基本控制器继承,我想知道我怎么能利用一切从基本控制器的逻辑,但返回比基控制器使用了不同的看法。
I have a controller that's inheriting from a base controller, and I'm wondering how I can utilize all of the logic from the base controller, but return a different view than the base controller uses.
该基地控制器填充一个模型对象,并将该模型对象的看法,但我不知道我怎么可以访问模型对象的子控制器,这样我可以把它传递给孩子控制器的视图。
The base controller populates a model object and passes that model object to its view, but I'm not sure how I can access that model object in the child controller so that I can pass it to the child controller's view.
推荐答案
根据这一线索给出的反馈,我实现了像安东尼·科赫提出的一个解决方案。
Based on the feedback given on this thread, I've implemented a solution like the one proposed by Antony Koch.
而不是使用抽象方法,我用一个具体的,虚拟GetIndex方法,这样我可以把逻辑在它的基础的控制器。
Instead of using an abstract method, I used a concrete, virtual GetIndex method so that I could put logic in it for the base controller.
public class SalesController : Controller
{
// Index view method and model
public virtual ActionResult GetIndex()
{
return View("Index", IndexModel);
}
protected TestModel IndexModel { get; set; }
public virtual ActionResult Index()
{
ViewData["test"] = "Set in base.";
IndexModel = new TestModel();
IndexModel.Text = "123";
return GetIndex();
}
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Index(TestModel data, FormCollection form)
{
TryUpdateModel(data, form.ToValueProvider());
IndexModel = data;
return GetIndex();
}
}
// This class will need to be in a different namespace or named differently than the
// parent controller
public class SalesController : MyApp.Controllers.BaseControllers.SalesController
{
// Index view method and model
public override ActionResult GetIndex()
{
return View("ClientIndex", IndexModel);
}
public override ActionResult Index()
{
return base.Index();
}
[AcceptVerbs(HttpVerbs.Post)]
public override ActionResult Index(TestModel data, FormCollection form)
{
return base.Index(data, form);
}
}
这篇关于我怎么能继承一个ASP.NET MVC控制器和仅改变看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!