Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file inside views folder in ASP.Net MVC 4.0

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?

like image 657
davy Avatar asked Mar 28 '13 16:03

davy


People also ask

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

What is the use of _layout Cshtml in MVC?

So, the _layout. cshtml would be a layout view of all the views included in Views and its subfolders. The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder.

How can we pass the data from Controller to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

How do I navigate to another view in MVC?

Call the appropriate /controller/action in your respective button click handlers. In your case for the register button handler direct it to /home/register. Have a view for your register functionality. In the register action of your home controller return the view you want to show.


1 Answers

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"];
like image 97
webdeveloper Avatar answered Oct 12 '22 00:10

webdeveloper