【问题标题】:Adding a sub-folder under Area and configuring View Engine to search the views in the sub-folder在区域下添加子文件夹并配置视图引擎以搜索子文件夹中的视图
【发布时间】:2020-05-11 10:13:35
【问题描述】:

我正在开发一个电子商务网站。该网站连接到多个第三方应用程序,例如 Shopify。为此,我创建了一个区域并称为 B2b(企业对企业)......

我想在B2b 区域下为这些第 3 方中的每一个创建一个子文件夹,因此文件夹结构如下所示:

请注意,OrganisationController 是所有 3rd 方共有的,所以我没有将它放在任何子文件夹中。

这是我的区域注册代码:

public class B2bAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get { return "B2b"; }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Shopify_default",
            "B2b/Shopify/{controller}/{action}/{id}",
            new { controller = "Dashboard", action = "DisplayProducts", id = UrlParameter.Optional },
            new[] { "e-commerce.Web.Areas.B2b.Controllers.Shopify" }
        );

        context.MapRoute(
            "B2b_default",
            "B2b/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

现在,如果我尝试以下网址:

https://localhost:44339/b2b/shopify/setup/install?shop=some-name

它会命中正确的控制器:

[HttpGet]
public ActionResult Install(string shop)
{
    var myViewModel = new MyViewModel(shop);
    return View(myViewModel);
}

但是视图引擎无法找到正确的视图,这是我得到的错误:

如您所见,View Engine 并未搜索 Shopify 子文件夹。我想我可以通过返回视图的路径来解决这个问题,但我想知道是否有更优雅的解决方案?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing asp.net-mvc-areas


    【解决方案1】:

    我在this tutorial的帮助下解决了这个问题

    我创建了一个自定义的 Razor 视图引擎:

    public class ExpandedViewEngine : RazorViewEngine
    {
        public ExpandedViewEngine()
        {
            var thirdPartySubfolders = new[] 
            {
                "~/Areas/B2b/Views/Shopify/{1}/{0}.cshtml"
            };
    
            ViewLocationFormats = ViewLocationFormats.Union(thirdPartySubfolders).ToArray();
    
            // use the following if you want to extend the partial locations
            // PartialViewLocationFormats = PartialViewLocationFormats.Union(new[] { "new partial location" }).ToArray();
    
            // use the following if you want to extend the master locations
            // MasterLocationFormats = MasterLocationFormats.Union(new[] { "new master location" }).ToArray();   
        }
    }
    

    并在Global.asax中配置网站使用上述视图引擎:

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            ViewEngines.Engines.Add(new ExpandedViewEngine());
            AreaRegistration.RegisterAllAreas();
    
            // more configuratins...     
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多