ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

Starting Out With ASP.NET MVC Part 1

Written by
Published on
Modified on
Filed under
Starting Out With ASP.NET MVC Part 1

One of my weaknesses in programming is actively using MVC in my projects. Particularly ASP.NET MVC, since I am a .NET Developer. Most of the jobs that I've had have not required MVC and as far as my personal work goes, I've spent a good bit of time working on my own framework throughout the years, and it doesn't make sense to me to start over. But MVC is becoming more prevalent and more and more companies are jumping on that wagon, so it's time to revisit it once again.

A little MVC overview

The MVC (Model View Controller) pattern isn't anything new really. It's been around since the 70's in various implementations and for use in various GUI's. MVC's main goal is to separate a project into 3 distinctive components. Those are the Model, which takes care of the data layer on a website, a View, which is what the client sees, and the Controller which is the layer that interacts with the Model directly so that the View doesn't have to and also interacts with the View to inform it of Model changes.

The overall idea is to keep these elements separate from each other, so that different people if need be can work on each part without needing to know how the others work. There are various implementations of MVC spread across the board for different programming languages and frameworks, but today I'll be talking about ASP.NET MVC specifically. If you're going from .NET Web Forms to MVC, then you are in for a treat, and you can pretty much forget most of what you've learned about Web Forms as they won't apply here.


Let's create a new project

mvc 3

The first thing we need to do is to create a new project and select the MVC template, which will create the correct directory format and configure our project to make use of all of the MVC libraries. Click OK, and our resulting project should look something like this.

mvc 3

This is a fully working MVC website right from the start. It supports user roles and memberships and base templates that you can work with.

mvc 3

Let's add a new Controller


Controllers are just that. They control the data and the flow of data over to the Views. In ASP.NET MVC they are simply a class that inherit from the Controller class. In order to get a better idea of the process from beginning to end, let's add a brand new Controller to work with, and we will build it up from there.

mvc 3
mvc 3

We can just add a new empty Controller for now and I'll talk about the other Scaffolding options later on.

mvc 3

The IDE should have generated the appropriate Controller class and a new directory for our Views. ASP.NET MVC follows a convention over configuration pattern. This means less work for us as developers in order to get things up and running. Views go into directories named based on their Controllers, and we can leave it at that. Let's open up that fancy new Controller and add some new functionality to it. Currently it should look something like this.

mvc 3

If you run that, you will get an error. And that is because the Controller's Index method (or action as it's called in ASP.NET MVC), which is the Action that is called by default when no other is specified, is returning a View, which we have not created just yet. So let's replace that function with one that will work.


Let's add a View


Currently we're using our new Controller as the View by having it return HTML directly to the client. So let's cut that out, and a new View that we can work with.



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

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public string Index()
        {
            return "<h1>hello world</h1>";
        }
    }
}


With this new Index method, we're returning the HTML directly to the client without needing to specify a View. By default, URL routing uses the following, with controller being the name of the controller and action the name of the function that we are referring to, as routing rules.



/[Controller]/[ActionName]/[Parameters]


Parameters


On top of the Controller and Action we can also throw in parameters to the mix, and these come in the form of method parameters. For example:



public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }

        public string Welcome(string name)
        {
            return "hello: " + name;
        }
    }


The method parameters coincide with the URL querystring parameters. This is again, the whole convention over configuration thing. It just works and we don't have to worry about messing with that plumbing.

This is all well and good, but we need a View, otherwise we'll be working with a MC pattern. Visual Studio makes it easy to add a View, by just simply right clicking inside of our Index action and adding a new View directly from the context menu.

Adding a new View


A fresh View will be void of life.



@{
    ViewBag.Title = "View";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>View</h2>


It sets a title and a layout, which is the equivalent of a MasterPage in web forms, and it will contain all of our markup. So now we have a Controller and a View, no Model yet. But we can send some data from the Controller to the View. And we can do that with the ViewBag object.

The ViewBag is a dynamic object, which means you can put whatever you want in to it, whether it be a primitive type such as an int or a List or custom objects. The ViewBag object has no defined properties until you put something inside it. So let's do that now.


TestController.cs

// GET: Test
public ActionResult Index()
    {
        ViewBag.Quantity = 20;
        return View();
    }



@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@ViewBag.Quantity


You can pass any type of data to the Views using the ViewBag object from primitive types to more complicated objects. And while that does come in handy sometimes, it's not recommended to use for every single piece of data that you need to bring over to the View. And that is because we still have the Model layer to look at and implement. Which I will cover in the next post, as this one has run long already. This is just a small taste of ASP.NET MVC in its simplest form. There are still many many more concepts to cover. And also, I hope everyone notices how much more different MVC is in .NET than Web Forms. It's not just an entirely new pattern, it's also an entirely new framework.

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks