Friday, November 8, 2013

"Hello World!" Using One ASP.NET MVC 5 From the Visual Studio 2013 Empty Template

I am in the process of learning MVC 5 and Visual Studio 2013. I am not a stranger to MVC concepts, but I am new to ASP.Net. I thought this might be helpful for new ASP.Net students who have already played with the pre-built MVC 5 template and want to start their own app from scratch.

Update 2/10/2014 
To avoid confusion, I changed the title of this post. This is not how to build a complete sample MVC 5 site from the ground up; it is just a tutorial on getting the empty template running. MVC5 books are out now that will explain site construction in extreme detail.

Create an ASP.Net 4.5 Empty MVC 5 Project
Create a new project/solution.

Choosing the MVC template will load a complete web application shell including controller, views…etc. We want an empty MVC shell with no pre-built pages. Choose Empty (C#) and check MVC.

If you try to run or debug the app immediately after creation, you’ll get an error: “Server Error in ‘/’ Application. The resource cannot be found.” The template is missing the default controller and view needed to display properly.

In the solution explorer, twist open Views and App_Start. Notice that pages are completely absent from Controllers, Models and the root. The Views folder contains a web.config file thinly stocked with Razor definitions.


App_Start contains the RouteConfig.cs file which is where you’ll find the default controller and action definition. According to line 19, the app will look for a controller named “Home” to start.

Create the Default Controller “HomeController”
Right click on Controllers and go to [Add]-->[New Scaffold Item…]

Choose “MVC 5 Controller – Empty” and click [Add]

Change the name of the controller to “HomeController” so it agrees with the default in the RouteConfig.cs file. 

Open the HomeController.cs file and notice the default code returns the view for the Index action.

Create the Default View “Index”
Now we need to create the index.cshtml view that the controller is looking for. Right-click on the Home folder under "Views" in Solution Explorer. Choose [Add] à MVC 5 View page (Razor).


Change the name of the view item to “Index” to match the ActionResult in the Controller.

Open Index.cshtml and insert “Hello World!” between the div tags on lines 13/14.

Click Save, then [Ctrl]+[Shift]+W to view your page in a browser.

Success!










No comments:

Post a Comment