asp.net mvc 3 - 从其他控制器调用nonaction

时间:2012-08-05 09:10:05

标签: asp.net-mvc asp.net-mvc-3

我有2个控制器CustomerControllerPrivatemessageController

客户有一种不作为方法

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

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

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

我想从GetCustomerNavigationModel获取CustomerController值,因为我不想为PrivateMessageController重新创建相同的方法,这是否可以在ASP.NET MVC 3.0中使用?< / p>

2 个答案:

答案 0 :(得分:1)

这里有两种选择。

  1. 将方法设为public static:

        [NonAction]
        public static CustomerNavigationModel GetCustomerNavigationModel(Customer customer)
        {
            var model = new CustomerNavigationModel();
    
            .... _customerSerice...
            return model;
        }
    
  2. 创建一个基本控制器并在那里实现该方法。让两个控制器都来自您的基本控制器:

    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
    {
        ....
    }
    

答案 1 :(得分:0)

将方法重构为单独的类,并使用控制器中的该类。您也可以将方法设为静态,并使用以下方法从 PrivatemessageController 中调用它:

CustomerController.GetCustomerNavigationModel(customer);