asp.net-mvc Asp.net MVC - 我可以从不同的视图文件夹加载视图吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4551404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asp.net MVC - Can I load a view from a different view folder?
提问by Chase Florell
In my app I have a need to load the same view from two different controllers without placing the view in the shared views directory.
在我的应用程序中,我需要从两个不同的控制器加载相同的视图,而不将视图放在共享视图目录中。
Basically I have this folder structure
基本上我有这个文件夹结构
- Controllers
- EventsController.cs
- SearchController.cs
- Views
- Events
- Preview.aspx
- Search
- Events
- 控制器
- 事件控制器.cs
- 搜索控制器.cs
- 观看次数
- 活动
- 预览.aspx
- 搜索
- 活动
basically picture it much the same as here on stack overflow. You get a preview of a bunch of questions under the questions link, but you also get an identically formatted page when you do a search in the search bar. The views and viewmodels are presumably identical.
基本上,它与堆栈溢出时的情况大致相同。您可以在问题链接下预览一堆问题,但在搜索栏中进行搜索时,您还会看到一个格式相同的页面。视图和视图模型大概是相同的。
Since the view I need for search is exactly the same as the view I need for events, I'd like to reuse the same view. I would however like to avoid using the shared directory for this specific view.
由于搜索所需的视图与事件所需的视图完全相同,因此我想重用相同的视图。但是,我想避免为此特定视图使用共享目录。
So my two part question is ---
所以我的两部分问题是——
- Is this possible, and if so how?
- Is this bad practice?
- 这可能吗,如果可以,怎么办?
- 这是不好的做法吗?
回答by Erik Funkenbusch
Yes, you can. Simply return View("~/Views/Events/Preview.aspx")
.
是的你可以。简直了return View("~/Views/Events/Preview.aspx")
。
However, i would advise against it for a number of reasons. The biggest being that this will be non-obvious to anyone trying to modify the code later (maybe even you) and might lead to potential errors.
但是,出于多种原因,我建议不要这样做。最重要的是,这对于稍后尝试修改代码的任何人(甚至是您)来说都是不明显的,并且可能会导致潜在的错误。
A better approach might be to create a "Shared" view, or a shared partial view. My preference would be a shared partial view, then in your non-shared view render the partial view functionality you want.
更好的方法可能是创建“共享”视图或共享部分视图。我的偏好是共享局部视图,然后在您的非共享视图中呈现您想要的局部视图功能。
回答by xandy
- It's possible.
- I am not sure if you are using strong-typed views. But suppose it is, then it is a bit weird for me that you have Event search & Search with same View Model. Possibly separate them with two different view models and view would be better IMHO. Moreover, if you specify the name of view to load in controller, it is somehow considered to be coupling view and controller and it certainly not a good idea.
- 这是可能的。
- 我不确定您是否使用强类型视图。但是假设是这样,那么对我来说,使用相同的视图模型进行事件搜索和搜索就有点奇怪了。可能将它们与两个不同的视图模型分开,恕我直言,视图会更好。此外,如果您指定要在控制器中加载的视图名称,它会以某种方式被认为是耦合视图和控制器,这当然不是一个好主意。