Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify a custom location to "search for views" in ASP.NET MVC?

I have the following layout for my mvc project:

  • /Controllers
    • /Demo
    • /Demo/DemoArea1Controller
    • /Demo/DemoArea2Controller
    • etc...
  • /Views
    • /Demo
    • /Demo/DemoArea1/Index.aspx
    • /Demo/DemoArea2/Index.aspx

However, when I have this for DemoArea1Controller:

public class DemoArea1Controller : Controller {     public ActionResult Index()     {         return View();     } } 

I get the "The view 'index' or its master could not be found" error, with the usual search locations.

How can I specify that controllers in the "Demo" namespace search in the "Demo" view subfolder?

like image 554
Daniel Schaffer Avatar asked Mar 11 '09 01:03

Daniel Schaffer


People also ask

How do I navigate to another view in MVC?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.

Which is a default view search path for the Razor view engine?

By default Razor Pages are stored in Pages folder under project root.

Can we use view state in MVC?

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method.

How can we implement search in MVC?

Right click on controller Folder and select template Empty MVC controller. Right click on Index method and select Strong -typed view as shown in the following figure. In above code I have two html radiobutton and one html text box and simple submit Button. Press F5 and run you application.


1 Answers

You can easily extend the WebFormViewEngine to specify all the locations you want to look in:

public class CustomViewEngine : WebFormViewEngine {     public CustomViewEngine()     {         var viewLocations =  new[] {               "~/Views/{1}/{0}.aspx",               "~/Views/{1}/{0}.ascx",               "~/Views/Shared/{0}.aspx",               "~/Views/Shared/{0}.ascx",               "~/AnotherPath/Views/{0}.ascx"             // etc         };          this.PartialViewLocationFormats = viewLocations;         this.ViewLocationFormats = viewLocations;     } } 

Make sure you remember to register the view engine by modifying the Application_Start method in your Global.asax.cs

protected void Application_Start() {     ViewEngines.Engines.Clear();     ViewEngines.Engines.Add(new CustomViewEngine()); } 
like image 135
Sam Wessel Avatar answered Oct 02 '22 23:10

Sam Wessel