Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?
like image 744
Chase Florell Avatar asked Dec 29 '10 04:12

Chase Florell


People also ask

How can we navigate from one view to another view in MVC?

Call the appropriate /controller/action in your respective button click handlers. In your case for the register button handler direct it to /home/register. Have a view for your register functionality. In the register action of your home controller return the view you want to show.

How pass data from view to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.

How do you pass ViewModel to view?

The recommended way to pass the ViewModel to the View is to make use of the View method. The View method takes the model as one of the argument, which internally sets it to the ViewData. Model Property.


1 Answers

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.

like image 166
Erik Funkenbusch Avatar answered Nov 08 '22 11:11

Erik Funkenbusch