Nam Vo
Nam Vo

Reputation: 159

asp.net mvc 3 - call nonaction from other controller

I have 2 controllers CustomerController and PrivatemessageController

Customers has a nonaction method

private readonly ICustomerService _customerService; 
public Customer(....)   << autofac Ioc 
{
 }

    [NonAction]
    protected CustomerNavigationModel GetCustomerNavigationModel(Customer customer)
    {
        var model = new CustomerNavigationModel();

        .... _customerSerice...
        return model;
    }

I'd like to get GetCustomerNavigationModel value from CustomerController as I don't want to recreate the same method for PrivateMessageController, is that possible in ASP.NET MVC 3.0 ?

Upvotes: 0

Views: 548

Answers (2)

Paul Fleming
Paul Fleming

Reputation: 24526

Two options come to mind here.

  1. Make the method public static:

        [NonAction]
        public static CustomerNavigationModel GetCustomerNavigationModel(Customer customer)
        {
            var model = new CustomerNavigationModel();
    
            .... _customerSerice...
            return model;
        }
    
  2. Create a base controller and implement the method there. Have both your controllers derive from your base controller:

    public abstract class MyBaseController : Controller
    {
        [NonAction]
        protected CustomerNavigationModel GetCustomerNavigationModel(Customer customer)
        {
            var model = new CustomerNavigationModel();
    
            .... _customerSerice...
            return model;
        }
    }
    
    
    public class CustomerController : MyBaseController
    {
        ....
    }
    
    public class PrivatemessageController : MyBaseController
    {
        ....
    }
    

Upvotes: 1

Andreas Gehrke
Andreas Gehrke

Reputation: 135

Refactor the method into a separate class and use that class from your controllers. You can also just make the method static, and call it from PrivatemessageController using:

CustomerController.GetCustomerNavigationModel(customer);

Upvotes: 0

Related Questions