Question

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?

Was it helpful?

Solution

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"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top