Simple ASP.NET MVC views without writing a controller

后端 未结 5 494
一整个雨季
一整个雨季 2021-01-04 10:50

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

5条回答
  •  被撕碎了的回忆
    2021-01-04 11:26

    Reflecting on Paul's answer. I'm not using any special view engines, but here is what I do:

    1) Create a PublicController.cs.

    // GET: /Public/
    [AllowAnonymous]
    public ActionResult Index(string name = "")
    {
        ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
        // check if view name requested is not found
        if (result == null || result.View == null)
        {
            return new HttpNotFoundResult();
        }
        // otherwise just return the view
        return View(name);
    }
    

    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.

    3) Then modify RouteConfig.cs to redirect to the Public/Index action.

    routes.MapRoute(
        name: "Public",
        url: "{name}.cshtml", // your name will be the name of the view in the Public folder
        defaults: new { controller = "Public", action = "Index" }
    );
    

    4) Then just reference it from your views like this:

    YourPublicPage 
    

    Not sure if this is any better than using a factory pattern, but it seems to me the easiest to implement and to understand.

提交回复
热议问题