Custom Search

How to learn MVC

For advanced users. This page is dedicated to intermediate to advanced users. I created this section to make it easier to navigate to a quick guide such as WCF, MVC, Ajax, etc. This way you are not left helplessly scrolling through an endless amount of information you already know and can get to the important concepts for learning. Although I am still a Junior Developer, I will be providing some examples to get you started using MVC.

Please note that since these pages are still being developed some of the navigational links above will only link to this page until I create the content for them. However I left them there to show you one of the reasons to refer back to this site will be a friendlier interface. That has been my goal as a programmer for years. I always like friendly applications that get you where you need to go. So stay tuned because I promise they are in process.

Microsoft's MVC (Model View Controller) is especially handy for creating applications. It consists of a process of diving an application into three components, which are the Model, The View, and the Controller. The Model represents the classes that express the concepts of the data that is being used, how it can be modified and manipulated. The View is comprised of the application's user interface (UI). Finally the Controller is made up of classes that communicate with users, handle how applications work sequentially, and help define the logic.

Introduction to asp.net MVC

Once you have launched Visual Studio 2010 select the File menu, New, and then Project. In the installed Templates section click on Visual C#. Then in the center screen search for ASP.NET MVC 2 Web Application and click on it. The default name is WebApplication1. Change this to MvcTestProject. If you are satisifed with the Location then click the OK button. Here is a screenshot.

learning asp.net mvc

Next a dialogue box called Create Unit Test Project will pop up. Make sure the option for Yes, create a new unit test project is selected and that Test framework shows Visual Studio Unit Test . The test project name will show MvcTestProject.Tests. If all is well click on OK.

mvc tutorial asp.net

Next a solution will occupy the Solution Explorer window with a series of projects. However focus your efforts on the folders that show Controllers, Models, and Views since these will be the main ones used in this lesson. They also make up the core of how MVC works.

learn .net mvc

Your First Controller Method

You are now ready to begin creating your own MVC projects based on the code you see below in the screenshot. First I will show some of the sample screens and then how to modify the Controller projects to your advantage.

Next expand the Controllers tab until you see HomeController.cs. This is the C# code for the project you will be creating from the existing template.

Be sure to change the code in the window so that it reflects the new changes shown in this screenshot for your convenience. I have highlighted the code to reflect the new changes to the code.

asp.net mvc section

The new change is creating a new page called Foo that will return a View. Now it is time to see this in action. Run the program by clicking on the green arrow on the Visual Studio toolbar. Make sure to accept the pop up to enable a change to your web.config file by clicking OK when you are prompted. After this your browser will open to show the Home MVC page. I am using Firefox in this example. Take a look.

mvc web development

The Foo method in a browser window

However to see the page you just created type this in your browser address bar http://localhost:3511/Home/Foo. Also be aware that your localhost number may be different. So make sure to leave that intact and just type the /Home/Fooafter it. If all goes well you should be looking at a screenshot similar to the following. You are now looking a the new Foo page you created earlier.

The page is resting at a breakpoint you created in the Foo method in your code located inside the HomeController.cs directory. MVC has sent a request to a handle called MvcHandler. This made the HomeController created and instance which activated the Foo method. The part in the code that shows ViewData passed information to a View that allowed the HTML to show up in the browser. Here is the new screenshot.

mvc applications

The Global.asax.cs file

Now it is time to dig deep below the surface of MVC to see how this is all happening. Glance over at the Solution Explorer on the right and open the file called Global.asax.cs. This file contains useful information about something called Routing. Routing specially locates the URL entry for each name in the dash separations. When you saw the earlier example /Home/Foo you were witnessing routing in action.

In this next section you will see how to take apart the method in Global.asax.cs to create your own paths to be found at a new URL you specify. First examine the screenshot for the default configuration for Global.asax.cs below. Once again I have highlighted the section within the method that we will be focusing on.

asp.net applications

Now change the Global.asax.cs so it is identical to the code shown in this next screen shot.

asp.net source

When you run the application again this time you will receive an error message in the browser window. The reason for this is when you changed the Global.asax.cs file earlier you interrupted the default routing for {controller}/{action}/{id}. By changing this to {store}/{products}/{cart} you have created a new routing path for the URL.

asp.net mvc search

To see your new page change, add the extension of /store/products/cart by appending it to the localhost: you already see in the window. You should now see the new store page as listed in the next screenshot.

asp.net mvc project

You may be wondering why all the pages look the same. However by adding the new URL extensions you are actually looking at those created routing URLs. I will add some code below now to show you that this change has taken effect for your new page.

However before you can see this working correctly you will need to restore the Global.asax.cs file so it corresponds to the exact output in the next screenshot here.

webforms mvc

After this change the HomeController.cs file exactly as listed below in this new screenshot. Then run the program again and navigate to the extension of /Home/Foo. Notice how you can add your own html inside of the Response.Write command.

understanding asp.net mvc

HTML content on your new page

Remember as mentioned earlier that you must use your own localhost to see this new change. My example looks like http://localhost:3511/Home/Foo. Time to view the new look for our page.

mvc in asp

This completes the first lesson for MVC. This lesson showed you how to create a new Controller class to create a new page, modify the Global.asax.cs file to see how routing works, and see some html content on your new page.

Code view

The HTML source code is below.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcTestProject.Controllers { [HandleError] public class HomeController: Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcTestProject.Controllers { [HandleError] public class HomeController: Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } public ActionResult Foo() { ViewData["Title"] = "Foo Page"; return View("Index"); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcTestProject { // Note For instructions on enabling IIS6 or IIS7 class mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication: System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{"pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults } public void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcTestProject { // Note For instructions on enabling IIS6 or IIS7 class mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication: System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{"pathInfo}"); routes.MapRoute( "example", // Route name "{store}/{products}/{cart}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults } public void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcTestProject { // Note For instructions on enabling IIS6 or IIS7 class mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication: System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{"pathInfo}"); routes.MapRoute( "simple", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults } public void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcTestProject.Controllers [HandleError] public class HomeController: Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); public ActionResult Foo() { ViewData["Title"] = "Foo Page"; Response.Write("<p&gt<p&gt<h1&gtThis is the new page for the shopping cart application.</p></p>&lt/h1>"); Response.Write("&ltp&gt"); Response.Write("<font color='yellow'&gt"); Response.Write("&ltb>Notice that the page can accept html commands directly by using Response.Write"); Response.Write("</font>"); return View("Index"); } } }
Subscribe to my newsletter
Privacy Notice: Programmer Mind will not compromise your privacy