Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to share action methods between different controllers. Take for example the following 2 controllers:

public class AController : Controller
{
       public ActionResult Index()
       {
           //print AController - Index
       }

       public ActionResult Test()
       {
           //print test
       }
}

public class BController : Controller
{
     public ActionResult Index()
     {
         //print BController - Index
     }
}

Both controllers have an Index method which is different. The Test method however can be called from both controllers. So I want that when the following urls are entered the Test() method will execute:

  • AController/Test
  • BController/Test

I would appreciate any suggestions on how to achieve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming the implementation of the Test() action is the same for both controllers, refactor it into a common service:

public interface ITestService {
    string Test();
}

public TestService: ITestService {
    public string Test() {
        // common implementation
        return "The test result";
    }
}

Then set up Dependency Injection to acquire this service.

Your controllers then can use the common service.

public class AController : Controller {

    private readonly ITestService _testService;

    public AController(ITestService testservice) {
        _testService = testservice;
    }

    public ActionResult Test() {
        var vm = new TestViewModel();
        vm.TestResult = _testService.Test();
        return View("Test", vm);
    }
}

public class BController : Controller {

    private readonly ITestService _testService;

    public BController(ITestService testservice) {
        _testService = testservice;
    }

    public ActionResult Test() {
        var vm = new TestViewModel();
        vm.TestResult = _testService.Test();
        return View("Test", vm);
    }
}

Because the View Test.cshtml is rendered by both controllers, it should be placed in the ViewsShared folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...