Get file inside views folder in ASP.Net MVC 4.0
Asked Answered
C

1

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?

Carpophore answered 28/3, 2013 at 16:18 Comment(3)
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.aspxWithal
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.Carpophore
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?Withal
J
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"];
Jochbed answered 28/3, 2013 at 16:45 Comment(2)
thanks, please see the comment above. The controller used is generic and always returns 'PageController', which is not too helpful.Carpophore
@Carpophore I agree with Justin, you should look at reflection.Jochbed

© 2022 - 2024 — McMap. All rights reserved.