Asp.net-mvc – Asp.net MVC – Can I load a view from a different view folder

asp.net-mvc

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

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 —

  1. Is this possible, and if so how?
  2. Is this bad practice?

Best Answer

Yes, you can. Simply 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.