Modern Web Development - Part 1

This is the first of ten parts of this blog post. The topics will be:

In the past year I’ve had a side project. FirstInked’s Beta recently shipped and I wanted to share with you what I’ve learned. To start out, I want to specifically thank two people who were really great in helping me formulate the strategies I’ll talk about. They are:

  • Dave Ward (@encosia) answered every twitter pleading with great advice.
  • Chris Rauber (@chrisrauber) was instrumental in doing the initial groundwork on the web project.

Where I Came From

I am not new to website development, but with most of my work taking me into the RIA space five years ago, a lot had changed in the interim. Back 10 years ago, much of the web code I saw and wrote looked a lot like this (and no, my blog code doesn’t look like this):

<html>
<head>
  <script type="text/javascript">
    function onInit() {
      var obj = document.getElementById("foo");
      foo.display = "block";
    }
  </script>
<head>
<body onload="onInit()">
  <div id="foo" style="display: none" height="100px">
    <font size="3" color="red">Hello World</font>
</div>
</body>

The mixing of the code, markup and styling was the de facto style back then but that doesn’t mean it was a good idea. It was easier with ASP.NET (classic) to do things this way. I relied a lot more on post-backs than client-side code which wasn’t the best experience for users. Something had to give.

What Has Changed?

While I’ve dabbled in Routing and MVC for the server-side code, I hadn’t gotten knee deep into the client-side richness now possible with the likes of jQuery and CSS3. ASP.NET MVC 3 has a lot to offer the web developer, but for this article series I am going to focus in on the client-side story since that is where most of the big changes are (at least in my eyes). I found that in building FirstInked that I spent about 20% of my time on the server code and the other 80% on the client code. This number is undoubtedly skewed by the fact that I am super comfortable with the server code and was learning the client code. But I think those numbers indicate a larger sense of what is happening. If your site isn’t about just displaying information (e.g. just information like a news site or blog) that you will be creating a lot more client-code than back in the first generation of web applications.

An Example

To set some context, let’s take a quick example and build a simple home page using the tools I’ll be talking about.

To start out, I create a new ASP.NET MVC 3 Project. This opens the “New ASP.NET MVC 3 Project” template page:

NewMvc

For any new development I do, I start with an empty project (though the Internet Application can be used if you want authentication and some basic start pages). I will be using Razor and HTML5 so I want to pick both the View Engine and make sure I click the “Use HTML5 semantic markup” checkbox. You can create a unit test project if you like (and you should) but I am going to skip that part for this series.

I start with a simple ASP.NET MVC 3 Empty project (for simplicity). The empty project has no controllers or views yet (though it has a _Layout…e.g. master page using HTML5). I want to clean up the project to be ready for what I want to build.

First, I look in the Scripts folder to see what scripts were added to the project by default. As I won’t be using any of the Microsoft AJAX stuff, I delete them:

deletemssripts

I am relying completely on the jQuery stack for my development so the Microsoft scripts aren’t needed.

The next thing I do is upgrade the version of jQuery. The stock ASP.NET MVC 3 ships with the 1.5.1 version of jQuery but using the package manager (assuming you’re using Nuget, which if you aren’t you should be) you can just upgrade both jQuery and jQuery UI which I will use extensively. When you open the “Manage NuGet Packages” dialog, you will want to click on “Updates” to update some of the built-in packages:

nuget

I always update the JQuery UI library (since that will update the jQuery library too). You may want to update all the packages, but these are the two that are key to what we’ll talk about. Now that we’ve updated the packages, we’ll need to update the versions on the layout page:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>@ViewBag.Title</title>
  <link href="@Url.Content("~/Content/Site.css")" 
        rel="stylesheet" 
        type="text/css" />
  <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" 
          type="text/javascript"></script>
  <script src="@Url.Content("~/Scripts/modernizr-2.0.6-development.min.js")" 
          type="text/javascript"></script>
</head>
<body>
  @RenderBody()
</body>
</html>

Now that I have the project ready, I want to add a new controller so I right-click the controller folder and add a new Controller:

newcontroller

For my needs I want an empty controller (as the scaffolding of a model doesn’t make sense for this simple example):

newcontrollerdialog

This results in a new controller file with a single result for “Index”. To create the view I need to right-click the Index method and pick AddView:

newView

This will bring up the Add View Dialog:

newviewdialog

I am leaving the view name so that the controller will find this view when I navigate to it. Again, I am only using Razor for my code so I leave that too. If I were using a model class, I’d use a strongly-typed view but for my needs, no model class. Finally, I want to use MVC 3’s Layout class so I leave the master page empty. This leaves us with a very simple home view razor file:

@{
  ViewBag.Title = "Index";
}
<h2>Index</h2>

I am going to focus on the client-side so I won’t put much razor syntax in this file. I have found that keeping a per-view .js and .css file for each page that requires it (not every page will require specialized styling or code, but for this example, I’ll use both). So my new razor file is:

@{
  ViewBag.Title = "Index";
}
<link rel="stylesheet" 
      href="@Url.Content("~/Content/Home.Index.css")" />
<h2>
  Index</h2>
<section id="main-section">
  <div>
    This is a client-side example!</div>
  <button>
    Click me to add some elements!</button>
</section>
<script type="text/javascript" 
        src="@Url.Content("~/Scripts/Home.Index.js")"></script>

(For you MVC veterans, you are already thinking ahead, be patient and stop trying to fix problems…we’re going to get to it.)

This is a big part of what I want to show is that separating the concerns into structure, look and code (e.g. Markup, CSS and JavaScript).

Since I am using jQuery, my JavaScript will just add some event handlers via jQuery in the document ready handler:

$(document).ready(function () {
  $("#main-section button").on("click", function () {
    $("#main-section").append("<div>New Div</div>");
  });
});

(Again, if you’re a jQuery veteran…wait for the bigger picture in upcoming posts…promise!)

Finally, I will style the page with some CSS:

#main-section
{
  font-size: 85%;
  border: black 1px solid;
  background-color: #ddd;
  width: 85%;
  margin-left: auto;
  margin-right: auto;
}

Putting this all together, we get a page that handles the mouse click and some basic styling:

example

You’ll notice that I named the JavaScript and the CSS based on the view and that’s mostly for discoverability while I am doing development. These scripts/stylesheets will be in addition to site-wide scripts and we’ll see later a better way of architecting this. But the general idea to take from this first part is that each view/partialview will consist of mostly these three parts:

  • Markup (HTML/Razor)
  • Design (CSS)
  • Code (JavaScript)

My goal is to finish this series in the next couple of weeks so keep an eye on a part every 2-3 days. You can get the source for what we have so far here:

 

Comments

Gravatar

Martin Randall Monday, January 16, 2012

Great start! Thanks from all those like me who thinking that they should be looking beyond Xaml for the next web technology. It's been a few years for myself since I did a ASP.Net application and the developments in web-based applications (as opposed to Silverlight, for instance) has largely passed me by.

Gravatar

Paul Tuesday, January 17, 2012

I'm in the same boat as you, having been buried in Silverlight for the last few years, so I'm looking forward to the rest of this series. Wow - Javascript has changed! Looking forward to #3 as there's only so much 'alert(error)' I can stomach :-P

Gravatar

Carl Cubillas Wednesday, January 18, 2012

THis is great! Looking forward to the next post of the series.

Gravatar

Ricardo Wednesday, January 18, 2012

Thanks! It is very educational to "peek" over a veteran programmer's shoulder.

Gravatar

Jason Gayda Wednesday, January 18, 2012

Shawn, this is an awesome start to something I've been wanting to see forever! thank you!

Gravatar

Frans Bouma Thursday, January 19, 2012

"This is a big part of what I want to show is that separating the concerns into structure, look and code (e.g. Markup, CSS and JavaScript). "

I know it's a small example and all, but as I'm an old fart who started webdev in 1994 with perl, I don't really know how you want to achieve this, as your example shows you embed HTML writing directly into the javascript (the div tag). While this might be the whole purpose of it, it's also a problem: with that code, you embed layout HTML inside the code, so you have the layout fragmented and not separated at all.

What I'm wondering is: how is this solvable with these new technologies, as IMHO it's required to solve it if you want a maintainable codebase: when using server-side code, the html writing is actually in the same spot as the html (ala asp classic) or in a code behind which enables/disables pieces of HTML in the HTML part, but with javascript it's not.

Gravatar

Shawn Wildermuth Thursday, January 19, 2012

Frans,

If you're patient and see where I am going, I think you'll see this. I agree the adding a div is a lousy example...in the next couple parts, I think you'll see what I mean...

Gravatar

Frans Bouma Thursday, January 19, 2012

cool, thanks :)

Gravatar

Iljia Injac Thursday, January 19, 2012

Hi Shawn!Clear, informative and helpful! Thank you!

Gravatar

Chris Love Thursday, January 19, 2012

Good start! You are a few years behind my experience in essentially relearnning how to build a moondern web application. I probably spend about 1% of my time in the server C# code these days. But it took a while to accept the fact I need so little on the server anymore except an initial page and some service end points to create a kick-ass native-like application.

Also, just a helpful tip, put the JS files below the closing body tag. Your page will render so much faster (read the Stephen Souders books, they will rock your world).

Gravatar

Shawn Wildermuth Thursday, January 19, 2012

Chris,

I told you to be patient..we're getting there.

Gravatar

Ras Fred Friday, January 27, 2012

leave the <spelling>mater</spelling> page empty

Gravatar

Geminica Monday, January 30, 2012

As another who started in web dev in the mid-90s and has let some skills/approaches get out of date, I'm finding this series very helpful already. Thanks!

Gravatar

Stephen Tuesday, February 7, 2012

I've been doing software since 1985, and I find development in C# quite easy, and I've also found MVC 3 quite easy. What throws me is the HTML,CSS,Javascript client side - the details, and the "big picture". I've been working with it, but find that it moves so fast I'm always behind. This looks like a very promising shortcut to get me up to speed! Looking forward to it, Shawn :). I'm glad that you've oriented it to the MS tools as well. Not necessarily because they are the best, but because it's what I use - and being able to follow the examples in your own toolset is invaluable.

Gravatar

Octavio Garfio R. Friday, February 10, 2012

Hi Shawn, very clear , you are an excelent teacher and software developer, I followed in the silverlight and now with ASP.MVC . Thanks.

Gravatar

Thaicarrot Sunday, February 12, 2012

Hi Shawn,
Great! But I would like to use jQuery UI Widget to deal with about UI rather than just jQuery

For me
JavaScript can be used with Infrastructure.
jQuery can be used with Behavios
jQuery UI Widget is for UI

Best Regards
Weera

Gravatar

NIkram Wednesday, February 15, 2012

this is good,
need to know step by step guide on Partial Views, or refer me link.
thanks!

Gravatar

Mechi Thursday, June 7, 2012

Great one boss, but please am new to ASP.NET MVC and i have been anticipating to be one of the best website developer in my country. please i will like u to be of help on where and how i can get the best material for MVC ?
Thanks


Leave a Comment

*
*
*