6

I need to retrieve the name of a single view inside a views\something folder (comes from request) within MVC 4.0 and I'm not sure of how best to do it.

My code works but it has a 'hacky' feel to it and I was hoping someone could be simplified.

My code looks like:

    private FileInfo GetNameOfViewToServe()
    {
        var LeftPartOfUri = Request.Url.GetLeftPart(UriPartial.Authority);
        var folder = Request.Url.AbsoluteUri.Replace(LeftPartOfFolderUri,string.Empty);
        var directory = new DirectoryInfo(Server.MapPath(@"~\Views\" + folder));
        return directory.GetFiles().First();
    }       

Is there a more elegant way to achieve this?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
davy
  • 4,474
  • 10
  • 48
  • 71
  • Any reason you don't store it in a database and have a Name to indentify it? EG: http:\\mysite.com\submitreview -> db lookup for submitreview = ~\Views\submitreview.aspx – Justin Mar 28 '13 at 16:41
  • Yeah, unfortunately it's a brown field project and I have to work with what's there. I just need a more elegant way of retrieving a list of files (usually only one from the relative request path. – davy Mar 28 '13 at 17:00
  • can you show the controller action you are invoking? Since it is MVC, can't your controller have a generic action that takes a string parameter and you can use reflection to create the view or a factory-like pattern that would return the view based off the string key? – Justin Mar 28 '13 at 18:45

1 Answers1

4

Try this solutions from question ASP.NET-MVC . How to get the controller name from an url? OR Get ControllerName and ActionName and populate the ViewData in Master Page?

var controller = (string)RouteData.Values["controller"];
Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47