.NET MVC Call method on different controller
Can anybody tell me how to call a method on a different controller from within an action method? I don't want to redirect. I want to call a method on a different controller that returns a string and use the response within my action method.
Solution 1:
Sounds in my ears like you should refactor your application, and extract the functionality that generates the string out to a new seperate class (or reuse an existing class, if you have one that fits) and let both controllers use that class.
Solution 2:
You can use the following approach to invoke a method on the other controller:
var otherController = DependencyResolver.Current.GetService<OtherController>();
var result = otherController.SomeMethod();
This worked for me in ASP.NET MVC5. Hope that it will work for you as well.
Solution 3:
You can achieve this via the Action
method of HtmlHelper
.
In a view, you would do it like this:
@Html.Action("OtherAction")
However it's not straightforward to obtain an instance of HtmlHelper
in an action method (by design). In fact it's such a horrible hack that I am reluctant to even post it...
var htmlHelper = new HtmlHelper(new ViewContext(
ControllerContext,
new WebFormView(ControllerContext, "HACK"),
new ViewDataDictionary(),
new TempDataDictionary(),
new StringWriter()),
new ViewPage());
var otherViewHtml = htmlHelper.Action("ActionName", "ControllerName");
This works on MVC 3. You might need to remove the StringWriter
arg from the ViewContext
constructor for MVC 2, IIRC.
</hack>