Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple ASP.NET MVC views without writing a controller

We're building a site that will have very minimal code, it's mostly just going to be a bunch of static pages served up. I know over time that will change and we'll want to swap in more dynamic information, so I've decided to go ahead and build a web application using ASP.NET MVC2 and the Spark view engine. There will be a couple of controllers that will have to do actual work (like in the /products area), but most of it will be static.

I want my designer to be able to build and modify the site without having to ask me to write a new controller or route every time they decide to add or move a page. So if he wants to add a "http://example.com/News" page he can just create a "News" folder under Views and put an index.spark page within it. Then later if he decides he wants a /News/Community page, he can drop a community.spark file within that folder and have it work.

I'm able to have a view without a specific action by making my controllers override HandleUnknownAction, but I still have to create a controller for each of these folders. It seems silly to have to add an empty controller and recompile every time they decide to add an area to the site.

Is there any way to make this easier, so I only have to write a controller and recompile if there's actual logic to be done? Some sort of "master" controller that will handle any requests where there was no specific controller defined?

like image 374
Jake Stevenson Avatar asked Jun 09 '10 19:06

Jake Stevenson


People also ask

Can we create view without controller in MVC?

Of course not, then how can we fix it? In the MVC Framework, the controller class includes a method, HandleUnknownAction(), that executes whenever we attempt to invoke an action (or when we request a view that has no matching action method) on a controller that does not exist.

How can we call a view without controller in MVC?

1) Create a PublicController. cs. 2) Then create a Public directory in the Views folder, and put all of your views there that you want to be public. I personally needed this because I never knew if the client wanted to create more pages without having to recompile the code.

Can we create view without model in MVC?

If you don't want to create View Model then it is completely fine. You can loose some benefit like automatic client side validation ( data annotation). It means you have to do all validation by your self in client side and later on server side. This is simple way you can do that.

How do I write C# code in a view .cshtml file?

Go to solution explorer => Views Folder => Right-click on “Home” Folder >> go to “Add” >> Click on [New Item] as follow. Select MVC 5 View Page with Layout(Razor) from "Add New Item" window and provide the required name like "ViewPageWithLayout. cshtml" click on "Add" button as follow.


Video Answer


2 Answers

You will have to write a route mapping for actual controller/actions and make sure the default has index as an action and the id is "catchall" and this will do it!

    public class MvcApplication : System.Web.HttpApplication {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = "catchall" } // Parameter defaults
            );

        }

        protected void Application_Start() {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(new CatchallControllerFactory());

        }
    }

public class CatchallController : Controller
    {

        public string PageName { get; set; }

        //
        // GET: /Catchall/

        public ActionResult Index()
        {
            return View(PageName);
        }

    }

public class CatchallControllerFactory : IControllerFactory {
        #region IControllerFactory Members

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) {

            if (requestContext.RouteData.Values["controller"].ToString() == "catchall") {
                DefaultControllerFactory factory = new DefaultControllerFactory();
                return factory.CreateController(requestContext, controllerName);
            }
            else {
                CatchallController controller = new CatchallController();
                controller.PageName = requestContext.RouteData.Values["action"].ToString();
                return controller;
            }

        }

        public void ReleaseController(IController controller) {
            if (controller is IDisposable)
                ((IDisposable)controller).Dispose();
        }

        #endregion
    }
like image 104
Tacoman667 Avatar answered Oct 07 '22 20:10

Tacoman667


This link might be help,

If you create cshtml in View\Public directory, It will appears on Web site with same name. I added also 404 page.

[HandleError]
    public class PublicController : Controller
    {
        protected override void HandleUnknownAction(string actionName)
        {
            try
            {
                this.View(actionName).ExecuteResult(this.ControllerContext);
            }
            catch
            {
                this.View("404").ExecuteResult(this.ControllerContext);
            }
        }
    }
like image 34
yasin Avatar answered Oct 07 '22 18:10

yasin