简体   繁体   中英

How to call another controller function in MVC?

I have two controllers.

one is

 public partial class CatalogController : BaseNopController
    {

 [NonAction]
        protected IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(IEnumerable<Product> products, 
            bool preparePriceModel = true, bool preparePictureModel = true,
            int? productThumbPictureSize = null, bool prepareSpecificationAttributes = false,
            bool forceRedirectionAfterAddingToCart = false)
        {
 var models = new List<ProductOverviewModel>();
            foreach (var product in products)
            {
                var model = new ProductOverviewModel()
                {
                    Id = product.Id,
                    Name = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription = product.GetLocalized(x => x.FullDescription),
                    SeName = product.GetSeName(),
                };

}
}

another one is

public class HireController : BaseNopController
    {

        [HttpPost]
        public ActionResult CheckData(string submitButton)
        {
            switch (submitButton)
            {
                case "Yes":

                   // I want to call  CatalogController  --> PrepareProductOverviewModels
                case "No":
                    return RedirectToRoute("detailform");
                default:
                    return RedirectToRoute("detailform");
            }

        }
}

Inside Hire controller --> CheckData function , I want to call CatalogController -->PrepareProductOverviewModels(...) How can I do it??

It's protected , so unless your HireController derives from CatalogController , you can't call it. If, however, you put it in another class, such as a ViewModel class, and make it public , you can call it from your HireController .

It makes very little sense for that ViewModel to be protected or for it to be in your controller class.

如果您有需要在控制器之间共享的方法,那么您应该将这些方法分离为“帮助程序”类并让两个控制器调用该类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM