ASP.NET Core MVC目录结构中的控制器和视图

时间:2018-09-12 10:38:17

标签: asp.net-mvc directory-structure

我正在ASP.NET Core MVC中开发应用程序,我对控制器和视图的结构有一些疑问。总之,对于两种类型的用户,公司和投资者,应用程序具有相同的结构。

应用程序检测到哪种类型的用户已登录,并将菜单链接更改为Company/[controller]/[action]Investor/[controller]/[action]格式

目录结构如下:

Imagen estructura de directorios

控制器具有以下运行良好的路由标签:

[Route("/Company/[controller]/[action]")]
public class DashboardController : Controller
{...

我的视图有问题,它们具有相同的目录结构,因为它没有检测到相应的视图。我必须在每个动作中放置一个return View("Views/Company/Dashboard/Dashboard.cshtml"),并附带所有通往视图的路径,这对我来说很不好。对于具有部分渲染到同一子目录中其他视图的视图,会发生相同的事情。

示例:Company/Dashboard/Dashboard.cshtml包含:

<partial name="Users" />

Users.cshtml所在的目录中成为Dashboard.cshtml

InvalidOperationException: The partial view 'Users' was not found. The following locations were searched:
/Views/Dashboard/Users.cshtml
/Views/Shared/Users.cshtml
/Pages/Shared/Users.cshtml

这是为这种类型的应用程序实现目录结构的最佳方法吗?

有没有一种方法可以告诉mvc在同一目录中搜索视图? (这应该是自动的,但我认为放置路线或类似路线会停止工作)

谢谢。

编辑: 我刚刚添加了一个实现IViewLocationExpander

的新类
   public class ViewLocationExpander : IViewLocationExpander
    {
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            string[] locations = new[] 
            {
                "/Views/Company/{1}/{0}.cshtml",
                "/Views/Investor/{1}/{0}.cshtml",
                "/Views/Shared/{0}.cshtml"
            };

            return locations.Union(viewLocations);
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            context.Values["customviewlocation"] = nameof(ViewLocationExpander); 
        }
    }

我注册了

services.Configure<RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ViewLocationExpander());
            });

但是我仍然有问题。 现在,MVC可以访问“视图”,但是我无法区分“公司”视图和“投资者”视图。当我选择“投资者”菜单时,应用程序将加载公司的视图(我发现的第一个)

如何告诉菜单必须使用什么控制器?

                <li><a asp-controller="Dashboard" asp-action="Index">Company Dashboard</a></li>
                <li><a asp-controller="Dashboard" asp-action="Index">Investor Dashboard</a></li>

0 个答案:

没有答案
相关问题