Tutorial: Hello World using ASP.NET MVC

Post to Twitter

Microsoft recently released ASP.NET MVC at their Mix 2009 conference this past week in Las Vegas. What we will do today is learn the most basic of all web applications, the infamous “Hello World“.

There is one thing you should be familiar with to complete this tutorial: What MVC (Model View Controller) is.

With that out of the way you will need a to have Visual Studio installed, Visual Web Developer 2008 SP1 will work fine (I’m using Visual Studio Professional SP1). Once you have that setup according to Microsoft’s instructions make sure to then grab the actual ASP.NET MVC download and install it as well.

We should be ready to start so open up Visual Studio and create a new project and call it “MvcHelloApplication”:

Creating the MVC Project

On the next screen it will ask you if you want to create some tests for certain tools, just take the default here as we won’t be adding any unit tests in this tutorial.

Unit Tests

Once Visual Studio has finished generating the new project right-click on the “Controllers” folder so we can add a new controller class. Select: Add -> New Item

Adding the new controller class

We called the new controller “HelloController”. Now this is not necessary for this simple web application but I’m going to add a model to the project. I want to introduce how the model class comes into the picture, so bear with me. Right-click on the “Models” folder and select: Add -> Class. Call the new class “HelloPerson”.

Adding the Model class

Lets add the one line of code for the model class we just created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcHelloApplication.Models
{
    public class HelloPerson
    {
        // This is the line we add
        public String name { get; set; }
    }
}

Now go back to the controller class we created and we will add some code. First, add this to the top so we can reference our new model:

using MvcHelloApplication.Models;

Now we add the new method:

public ActionResult Greet(String theName)
{
    HelloPerson person = new HelloPerson();
    person.name = theName;

    ViewData["HelloName"] = person.name;

    return View();
}

So the final code looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

using MvcHelloApplication.Models;

namespace MvcHelloApplication.Controllers
{
    public class HelloController : Controller
    {
        //
        // GET: /Hello/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Greet(String theName)
        {
            HelloPerson person = new HelloPerson();
            person.name = theName;

            ViewData["HelloName"] = person.name;

            return View();
        }
    }
}

So all we are doing is capturing a value and then displaying it back out through the page that will render what is inside ViewData.

There are two more things we need to do before this will work. We need a page to render this out to as well as a small modification to the global.asax file.

Lets generate the view first. Right-click on the “Views” folder and add a new folder called “Hello”. Now right-click on the new “Hello” folder and and select: Add -> New Item. Then pick the “MVC View Content Page” and call the new file “Greet.aspx”.

Adding the view page

Take the defaults for the next dialog that pops up.

Take the default here...

We will modify the page now to render out the name for us. Add the following code to do that:

<strong>Hello <%=ViewData["HelloName"]%></strong>

The code should look like this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <strong>Hello <%=ViewData["HelloName"]%></strong>
</asp:Content>

The last thing we need to do is modify the global.asax file. Add the following to the “RegisterRoutes” method above the existing “routes.MapRoute” code:

routes.MapRoute(
    "HelloGreet",
    "Hello/{theName}",
     new
     {
         action = "Greet",
         controller = "Hello",
         theName = "Anonymous"
     }
);

If your a Ruby on Rails programmer this will probably look pretty familiar.

The final code would look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcHelloApplication
{
    // Note: For instructions on enabling IIS6 or IIS7 classic 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(
                "HelloGreet",
                "Hello/{theName}",
                 new
                 {
                     action = "Greet",
                     controller = "Hello",
                     theName = "Anonymous"
                 }
            );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

We are ready to try this out. Press “F5″ to get the project up and running. Change the URL in your browser to the correct port number and then add in the controller name as well as your own. In my case it was: http://localhost:1061/Hello/Chad

Final Result

Post to Twitter

This entry was posted in ASP.NET, C#. Bookmark the permalink.

9 Responses to Tutorial: Hello World using ASP.NET MVC

  1. Naim says:

    This is nice tutorial. It is simple but is useful for beginners. Can you post me some advanced links for model view control implementations.
    Thanks,
    Naim

  2. Wilkes says:

    thank you, microsoft dives right in with that huge NerdDinner tutorial, but fails to give us some of the simple ones first.

  3. Toba says:

    Thank you. a good head-start.

  4. Seo Dubai says:

    Thanks for post. Helped me start to learn MVC. That’s some brain scratcher.

  5. jobs says:

    great post, do you have one for data access too?

  6. Songchai@Gissoft says:

    Nice tutorial. Thank you very much.

  7. Mahadhir says:

    nice tutorial

  8. tom mcd says:

    This code is touchy! I didn’t EXACTLY follow the directions and got a 404 upon test. I didn’t “Add the following…ABOVE the existing routes”. I added it below the existing routes and got a 404. I once I moved it to the top everything worked.

  9. Yasharth says:

    Nice Man…..

    for beginners its the best ……

    Thanks

Comments are closed.