3

How exactly does one render a .cshtml file?

I'm new to ASP.NET. I've created an MVC project using Visual Studio's template. Apparently all the templates have .cshtml for the Default / Index files. But my server gives me this error when I try to view it:

Server Error in '/' Application. This type of page is not served.

Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.cshtml' may be incorrect. Please review the URL below and make sure that it is spelled correctly.

Requested URL: /mobile/WebApplication1/Index.cshtml

So, how exactly do I view the Index file? Do I need to pass it through something to convert to .html or render it somehow?

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
testing123
  • 761
  • 6
  • 13
  • 37

2 Answers2

4

Files with extension .cshtml in the context of ASP.NET MVC are views. They cannot be viewed (served by the web server) just by themselves. You need a controller action that will render the view.

NOTE: you could employ some "tricks" to modify IIS settings and your app to enable serving .cshtml files to browser requests, but this would not be normal behaviour.

Assuming your view is located at ~/Views/Index.cshtml here is a (trivial) example of a simple controller action:

public class ExampleController : Controller
{
    public ActionResult Index()
    {
         return View();
    }
}

This controller should be placed at: ~/Controllers/ExampleController.cs

You will access the rendered page at: localhost/example/index

More about ASP.NET MVC here: http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

Floremin
  • 3,969
  • 15
  • 20
3

You can not access an MVC view directly by its name. Ever...!

What you can do is call a Controller action, and that is done through an URL such as /WebApplication1/Index.

The above URL means two things:

  • there has to be a class called WebApplication1Controller.cs,
  • and that class must have a method public ActionResult Index().

The method Index will then determine which View (if any) is going to be displayed, and also what data will be sent to that view to use.

If the method Index executes return View(); then there is an implicit rule that the view with the same name (in this case Index.cshtml) is going to be shown.
Or if for some reason Index executes return View("Wow"); instead, then the view called Wow.cshtml will be displayed.

Peter B
  • 22,460
  • 5
  • 32
  • 69