views:

1562

answers:

2

Is it possible to display a view from another controller?

Say for example I have a CategoriesController and a Category/NotFound.aspx view. While in the CategoriesController I can easly return View("NotFound").

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.

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?

+12  A: 

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 \Views\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.

womp
Thanks, this sounds like the solution I should be using.I still wonder if it is possible to display a View from another controller though. I'm guessing this violates some rule in MVC?
metanaito
In the situation you describe above, yes, you should be using the Shared folder.
Jon Freeland
Yep, that is also possible. If you do return View("~/Views/Wherever/SomeDir/MyView.aspx")You can return any View you'd like. This doesn't violate any particular rule per se, however, ASP.Net MVC is all about "convention over congfiguration". In other words, the framework is built to operate automatically using certain conventions, and you should utilize it where possible.
womp
Thanks for the explaination. I didn't know Views could be called like that. The Shared directory of course works perfectly :)
metanaito
+2  A: 

you can also call any controller from javascript/jQuery say you have controller returning 404 or some other usercontrol/page then, on some action, from your client code you can call some adress that will fire your controller and return result in html format your client code can take this returned result and put it wherever you want in you your page...

mvc rocks, don't you think? :)

cheers

Marko
I did not know that. That sounds like it's something I might use in the future. Yes, mvc rocks :)
metanaito