2015-01-09 3 views
0

Я использую MVC nopCommerce и разработки пользовательских плагинов которые замещают существующие функциональные HomepageBestSellers (действие ProductController, который приписывается в качестве [ChildActionOnly]).nopCommerce Ошибка: действия по уходу за детьми не разрешается выполнять переадресацию действия

FilterProvider:

namespace Nop.Plugin.Product.BestSellers.Filters 
{ 
    public class BestSellersFilterProvider : IFilterProvider 
    { 
     private readonly IActionFilter _actionFilter; 

     public BestSellersFilterProvider(IActionFilter actionFilter) 
     { 
      _actionFilter = actionFilter; 
     } 

     public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) 
     { 
      if (actionDescriptor.ControllerDescriptor.ControllerType == typeof(ProductController) && actionDescriptor.ActionName.Equals("HomepageBestSellers")) 
      { 
       return new Filter[] 
       { 
        new Filter(_actionFilter, FilterScope.Action, null) 
       }; 
      } 

      return new Filter[] { }; 
     } 
    } 
} 

Action Filter:

namespace Nop.Plugin.Product.BestSellers.Filters 
{ 
    public class BestSellersFilter : ActionFilterAttribute 
    { 
     private readonly ISettingService _settingService; 
     private readonly IStoreService _storeService; 
     private readonly IWorkContext _workContext; 

     public BestSellersFilter(ISettingService settingService, 
      IStoreService storeService, IWorkContext workContext) 
     { 
      this._settingService = settingService; 
      this._storeService = storeService; 
      this._workContext = workContext; 
     } 

     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      //load settings for a chosen store scope and ensure that we have 2 (or more) stores 
      var storeScope = 0; 
      if (_storeService.GetAllStores().Count < 2) 
       storeScope = 0; 

      var storeId = _workContext.CurrentCustomer.GetAttribute<int>(SystemCustomerAttributeNames.AdminAreaStoreScopeConfiguration); 
      var store = _storeService.GetStoreById(storeId); 
      storeScope = store != null ? store.Id : 0; 

      var bestSellersSettings = _settingService.LoadSetting<BestSellersSettings>(storeScope); 

      if (bestSellersSettings.IsBestSellersEnabled) 
      { 
       filterContext.Result = new RedirectResult("Plugins/BestSellersProducts/PublicInfo"); 
      } 
      else 
       base.OnActionExecuting(filterContext); 
     } 
    } 
} 

Я получаю следующее сообщение об ошибке на filterContext.Result = новый RedirectResult ("Плагины/BestSellersProducts/PublicInfo"); эта линия:

Child actions are not allowed to perform redirect actions. 

Description: An unhandled exception occurred during the execution of the current web request. 
Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Child actions are not allowed to perform redirect actions. 

UPDATE:

  1. Изменено BestSellersFilter.cs в соответствии с ответом.

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        var storeScope = 0; 
        if (_storeService.GetAllStores().Count < 2) 
         storeScope = 0; 
    
        var storeId = _workContext.CurrentCustomer.GetAttribute<int>(SystemCustomerAttributeNames.AdminAreaStoreScopeConfiguration); 
        var store = _storeService.GetStoreById(storeId); 
        storeScope = store != null ? store.Id : 0; 
    
        var featuredProductsSettings = _settingService.LoadSetting<FeaturedProductsSettings>(storeScope); 
    
        if (featuredProductsSettings.IsFeaturedProductsEnabled) 
        { 
         var products = _productService.GetAllProductsDisplayedOnHomePage(); 
    
         BestSellersController objResult = new BestSellersController(); 
         filterContext.Result = new ContentResult { Content = objResult.PublicInfoPlugin() }; 
         //base.OnActionExecuting(filterContext); 
        } 
        else 
         base.OnActionExecuting(filterContext); 
    } 
    
  2. Изменено BestSellersController.cs в соответствии с ответом.

    public string PublicInfoPlugin() 
    { 
        var featuredProductsSettings = _settingService.LoadSetting<FeaturedProductsSettings>(_storeContext.CurrentStore.Id); 
        if (featuredProductsSettings.IsFeaturedProductsEnabled) 
        { 
        var products = _productService.GetAllProductsDisplayedOnHomePage(); 
        //ACL and store mapping 
        products = products.Where(p => _aclService.Authorize(p) && _storeMappingService.Authorize(p)).ToList(); 
        //availability dates 
        products = products.Where(p => p.IsAvailable()).ToList(); 
    
        if (products.Count == 0) 
         return ""; 
    
        var model = PrepareProductOverviewModels(products.Take(featuredProductsSettings.ShowFeaturedProductsNumber)).ToList(); 
        return RenderPartialViewToString("~/Plugins/Product.FeaturedProducts/Views/ProductFeaturedProducts/PublicInfo.cshtml", model); 
        } 
    
        return ""; 
    } 
    

Теперь получать Null значения из всех частных объектов в PublicInfoPlugin методом.

ответ

1

Вместо RedirectResult, установите его в ContentResult и установить Content свойство на выходе из действия вашего плагина:

filterContext.Result = new ContentResult { Content = "Load your plugin's action here" }; 
+0

Я попытался дать 'filterContext.Result = новый ContentResult {Content =«Плагины/BestSellersProducts/PublicInfo "};' но он возвращает ту же строку (то есть «Plugins/BestSellersProducts/PublicInfo»), а загружает ее. Я предполагаю, что метод не вызывает, и он принимает строку как результат. Как загрузить действие плагина здесь? –

+0

Вам необходимо создать экземпляр вашего контроллера плагина и вернуть действие вместо ActionResult. Все остальное в действии остается неизменным, за исключением того, что вы возвращаете Nop.Web.Framework.Controllers.BaseController.RenderPartialViewToString (string viewName, objectModel); вместо PartialView. Если ваш контроллер наследует от BaseController, вы получите его. – AndyMcKenna

+0

Когда я изменил свой тип 'ActionResult' на' string' с новым экземпляром контроллера плагина, как вы предлагаете, все остальные объекты получают нуль в контроллере плагинов. Мой вопрос обновлен, вы можете увидеть раздел обновления. –

Смежные вопросы