8

I'm using Asp.net MVC4 with razor. I want to know how to call a controller from one project to another project in a same solution. (I'm new to MVC4)

solution explorer screenshot

tereško
  • 58,060
  • 25
  • 98
  • 150
tishantha
  • 487
  • 5
  • 13
  • 34

4 Answers4

5

You can simply add your controllers to another project (class lib or MVC project, etc...) We have a couple projects that share controllers(webAPI as well as MVC). I typically use area constraints for the API controllers and namespace constraints for MVC controllers- especially if you have something like a base HomeController.cs used for some projects and you want to override it in just one particular MVC application project.

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "Common.MVC.Controllers" }
        );
bradodarb
  • 366
  • 3
  • 5
4

The answer depends a great deal on the concrete problem you are trying to solve.

This is something important to remember when asking questions on Stack Overflow. Sometimes it's more beneficial to ask how to solve your problem rather than how to accomplish the solution you've come up with.

If your goal here is to avoid code replication the simplest answer is to add your second project as a reference to your first. Accessing the controller is still a bit difficult because you need to instantiate it properly so what I'd recommend instead is that you abstract the code you wish to avoid replicating into a third project and have both your MVC projects make calls to the utility class you've created.

Another possibility is that you'd like to have your web services interact with each other while maintaining a client/server relationship. This can be achieved by creating an HTTP web request directed at the port number that Visual Studio selects when you run the second web service project. .Net is capable of doing this but personally I recommend using RestSharp.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
3

You have to seperate projects (because you are testing in local) and then run Destination project and get address (like http://localhost:15823/). After that, in another project's controller, use the following:

public ActionResult Index()
{
    return Redirect("http://localhost:15823/");
}

and run another project.

user3071284
  • 6,955
  • 6
  • 43
  • 57
-1

I kept running my other project whose links I was calling. So in short both applications must be running simultaniously.

  • That may work when running the application(s) locally, but this doesn't sound like it would work if the application is published online. – CaptainGenesisX May 16 '22 at 12:48