在 ASP.NET MVC 中显示来自另一个控制器的视图 [英] Display a view from another controller in ASP.NET MVC
问题描述
是否可以从另一个控制器显示视图?
Is it possible to display a view from another controller?
例如我有一个 CategoriesController
和一个 Category/NotFound.aspx
视图.而在CategoriesController
中,我可以很容易地返回View("NotFound")
.
Say for example I have a CategoriesController
and a Category/NotFound.aspx
view. While in the CategoriesController
, I can easly return View("NotFound")
.
现在假设我有一个 ProductsController
和一个用于添加产品的操作和视图.但是,此操作要求我们有一个要将产品添加到的类别.例如,Products/Add/?catid=10
.
Now say I have a ProductsController
and an action and view to add a product. However, this action requires that we have a Category to add the Product to. For example, Products/Add/?catid=10
.
如果我无法根据 catid
找到 Category,我想从 Categories 控制器显示 NotFound
视图,而不是创建 CategoryNotFound
在 Products 控制器下查看.
If I am not able to find the Category based on catid
, I want to show the NotFound
view from the Categories controller instead of creating a CategoryNotFound
view under the Products controller.
这是可能的还是我以错误的方式构建事物?有什么好的办法吗?
Is this possible or am I structuring things in the wrong way? Is there a good way to do this?
推荐答案
是的.默认情况下,ASP.NET MVC 首先检查 Views[Controller_Dir]
,但之后,如果没有找到视图,它会检查 ViewsShared代码>.
Yes. By default, ASP.NET MVC checks first in Views[Controller_Dir]
, but after that, if it doesn't find the view, it checks in ViewsShared
.
共享目录专门用于在多个控制器之间共享视图.只需将您的视图添加到 Shared 子目录即可.
The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.
如果你这样做 return View("~/Views/Wherever/SomeDir/MyView.aspx")
你可以返回任何你想要的视图.
If you do return View("~/Views/Wherever/SomeDir/MyView.aspx")
You can return any View you'd like.
这篇关于在 ASP.NET MVC 中显示来自另一个控制器的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!