0

Say I have a controller with these action methods:

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

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }
}

By convention I'll have three views having the same name of the methods.

But what if I want to add prefix to the view name? For example, in my case I'd like to add Controller name as prefix to the view name, so I'll have: HomeIndex, HomeAbout, HomeContact. Is there a way to obtain this by a configuration or do I have to explicitly pass the name for every View()?

NOTE I don't want to rename my action methods to

  • HomeIndex()
  • HomeAbout()
  • etc.

because I want to maintain URLs in the common format:

  • /Home/Index
  • /Home/About

I just want a different naming convention for my cshtml files, possibly without explicitly need to specify the name in View method.

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • 2
    Why would you want your urls to be `../Home/HomeIndex` and `../Home/HomeAbout` etc? –  Jul 20 '15 at 14:12
  • @StephenMuecke, As I can see, not URLs, but view paths, i.e. **/Views/Home/HomeIndex.cshtml**, and so on. – Mark Shevchenko Jul 20 '15 at 14:13
  • 1
    Name the methods `HomeIndex`, `HomeAbout`, and `HomeContact`, and then you can name your views the way you suggest above. However, your URLs will look like that too, unless you modify your routeconfig. – ragerory Jul 20 '15 at 14:13
  • You can name your views whatever you want - you just then need to specify the view name when returning the view - `return View("HomeIndex")` etc –  Jul 20 '15 at 14:16
  • Create a custom ViewEngine that inherits from `RazorViewEngine` and then override `FindView()` – mxmissile Jul 20 '15 at 14:16
  • This is not a duplicate of the linked question, that is talking about view location. Different beasts. – mxmissile Jul 20 '15 at 14:18
  • @mxmissile it is the same solution for more or less the same problem. If OP's question were _"I want my controller name as another subfolder, i.e. `~/Views/Home/Home/Index.cshtml`"_, (where subfolder == prefix in this question), the difference would be one slash in the locations. If I understand the question correctly, that is. – CodeCaster Jul 20 '15 at 14:20
  • I updated my question adding details. – davioooh Jul 20 '15 at 14:44
  • @daviooh you just expanded on what you want, you didn't really add new information with the edit nor do you show what you have researched. Did you check the duplicate? Doesn't that do what you want? The naming convention for views is registered in the RazorViewEngine; to alter this convention, you'll have to roll your own RazorViewEngine. The duplicate explains how. – CodeCaster Jul 20 '15 at 14:46
  • @CodeCaster thank you – davioooh Jul 21 '15 at 09:55

0 Answers0