1

我可以在不编写操作方法的情况下将 cshtml 页面作为视图提供吗?

那么,如果我有一个名为 Help 的控制器和一个名为 Money.cshtml 的视图,我想以 localhost/help/money 的身份访问它而不编写操作方法?

4

1 回答 1

3

You could do something like the following. Define a route that maps to just one action e.g.:

routes.MapRoute(
    "Help_default", // Route name
    "help/{path}", // URL with parameters
    new { controller = "About", action = "Page" }
);

Then your help controller could look like the following. It basically just grabs the path from the URL and passes that as the model to the view.

public class HelpController : Controller
{
    public ViewResult Page(string path)
    {
        return View("Page", path);
    }
}

Your Page view could then look like:

@model string

@{
    string viewPath = string.Format("~/Views/Help/{0}.cshtml", Model);
    ViewEngineResult result = ViewEngines.Engines.FindView(this.ViewContext.Controller.ControllerContext, viewPath, null);
    if (result.View != null)
    {
        @Html.Partial(viewPath)
    } else {
        // Define a not found view in the shared folder?
        @Html.Partial("NotFound")
    }
}

Which basically checks to see if a view exists with that path or not. It feels a bit dirty but I think it would work.

于 2013-04-16T17:19:58.767 回答