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?

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.aspx Commented Mar 28, 2013 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. Commented Mar 28, 2013 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? Commented Mar 28, 2013 at 18:45

1 Answer 1

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"];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, please see the comment above. The controller used is generic and always returns 'PageController', which is not too helpful.
@davy I agree with Justin, you should look at reflection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.