Comparing ASP.NET MVC and Web Forms

Before we get into MVC proper, let's discuss why you should consider MVC at all. It's my personal feeling that MVC 3 is going to be a horrifically important technology for all of us. If you're moving into more mobile development, MVC is going to be a much better choice. Secondly, in a HTML 5 world, MVC is going to be a better choice due to its ability to control HTML markup and reference client IDs via JavaScript. It's not to say ASP.NET Web Forms will not allow for this kind of development, but as the current Web Forms platform exists, it will be more difficult. An example of this..., having the ViewState be part of HTML pages on mobile browsers can have significant impact on load times. Okay, time to jump off the soapbox.

MVC stands for Model-View-Controller. In my mind, I think of it this way ... model is really our data or more correctly, business object. The model contains the data we want to render. The view is the page that we use to render the data. The controller is essentially the traffic cop that tells the data, what view it needs to go to. Most of this is handled automatically by MVC's concept of convention over configuration.

It all works something like this ... a user hits a URL and the controller gets called, based on routing rules it knows which controller to go to. The controller then loads the model from the database. Once the model is populated it then determines what view to load and passes the model to the view for rendering. One of the benefits of an approach like this is that the view is very lightweight with little code in the view proper. The code there is just for helping to render the data. This naturally leads to separation of concerns, which is always a good development practice that is hard to follow in Web Forms.

One of the reasons for converting a site to MVC is to create both an HTML 5 version of the site and a mobile HTML version. In this scenario the controller would load one version of the data (aka the model), but based on the type of browser accessing the site, pass the model to a different view, for example the HTML 5 view. You can get a glimpse of the power. No matter the type of site we have, we are always accessing our data in the same way and passing the view.

So, is ASP.NET Web Forms dead? Of course not! The real genesis of ASP.NET Web Forms was to provide an easier migration path for VB/Winform developers, who were familiar with event driven programming, into the stateless world of the web and web programming. Essentially, Web Forms abstract away the stateless nature of the web. As our paychecks prove, it's a great programming platform running millions of sites. Microsoft will continue to support Web Forms.

There are times when Web Forms will make sense, and times where MVC will make sense. At a high level:

Advantages of Web Forms:

  • Developer Familiarity
  • VERY rich eco system of server controls
  • Provides a RAD development environment
  • Event driven system
  • Much easier development for data heavy LOB system

Advantages of MVC:

  • Full control over HTML
  • Easy integration with JavaScript frameworks
  • Embraces the stateless nature of the web
  • Easier Search Engine Optimization
  • Allows for better testing

At the end of the day, both MVC and Web forms are platforms built on ASP.NET and use the same runtime. HTML and HTML 5, while always an important part of what we do, are becoming more and more important. If you ever needed verification of this, Microsoft's recent announcement that Windows 8 would allow for the distribution of HTML 5 apps to Windows reinforces that. MVC and Web Forms are both platforms we need to make our customer successful in this kind of environment. While I feel MVC is going to be a preferred platform for HTML development, the truth is both platforms are suited for the creation of HTML sites.

Why Use it? ASP.NET MVC is a platform for developing HTML applications that provides the user much greater control over the HTML markup that is rendered. There are added benefits such as supporting testing and better code design too!

I Want To Learn More!

Professional ASP.NET MVC 2(book)

ASP.NET MVC 2 in Action (book)

Pro ASP.NET MVC V2 Framework (book)

Microsoft ASP.NET MVC site- Check out the pluralsight videos on the page!

StackOverflow question on Web Forms vs MVC

Along this same line there is great NuGet package that you can use with MVC3 and EF 4.1 that will generate your views, controllers and Repositories. Yes, a code-gen tool that adheres to real world architecture practices, from your true POCO model classes. Check it out.


 

WebMatrix Proves an Excellent Tool for Creating Small Sites Quickly

As our work on the Appleton Compassion Project was wrapping up, Skyline took over ownership of the database that runs the site from the School District so we could easily make corrections and additions without having to download a new version of the database each night. Now that we "owned" the database, we realized we needed a way to maintain and manage it. For this we used Microsoft's new tool, WebMatrix.

Right about now you are asking yourself, really, another programming tool? An excellent question. WebMatrix is a response from Microsoft to Ruby on Rails and PHP. The benefit these development stacks is that they can generally be used to implement data driven sites relatively quickly and, until now, Microsoft didn't have a tool that allowed that.

While the .NET stack is a great development platform, it doesn't always allow for quick website development. As developers we tend to over-engineer sites, especially the ones that only need to be a couple of pages. We create a data layer, we create a business layer, and then we create a UI layer. These are, of course, industry best practices, but they are industry best practices for sites that are going to scale. If you're building a site for a couple of users who just want to see a list of their child's soccer games, this is definitely over engineering. WebMatrix is Microsoft's answer to that.

WebMatrix harkens back to the days of Classic ASP. It contains code logic in a single page, including the SQL statement. You can then render your page using Microsoft's new Razor engine.

Getting Started To get started, download WebMatrix using Microsoft's web platform installer. Upon starting up the application you'll see a nice, simple-to-use page that includes many templates you can use to get started with your development quickly and easily.

So, what does the code look like? Truthfully, it's really simple. Here is the basis of a page we used to create a list of all students participating in the Compassion Project.

The first thing to realize is the @{ } syntax is part of the Razor view engine. It is the replacement for <%= %> that tells the runtime you are escaping out to do something code like. Essentially, to get our list of data we do three things ... open a database connection, tell it the SQL command, and execute the SQL statement, the same three things we always do. In this case however, those three things are three lines:

@{
    var db=Database.Open("Dev");
    var sqlQuery = "select * from ProjectData order by LastName, FirstName";
    var data = db.Query(sqlQuery);
}

Next we have to render the output to the page. Again, we rely on the Razor View engine (look for the @ symbol):

<body>
    <ul>
        @foreach (var row in data) {
            <li><a href="EditArtist.cshtml?id=@row.PictureNumber">@row.PictureNumber</a> @row.LastName @row.FirstName</li>
        }
    </ul>
</body>

We are essentially saying for each (@foreach is Razor syntax) row in our data set (data is a globally scoped variable on the page), create a link to a key (@ is again the Razor syntax, so @row.PictureNumber tells the page to use the picture number) and create hypertext for the person's name. That's it! As you can see from the code snippets above, it takes very few lines to get data from a database.

The update part is also similar. It is, of course, longer since there is a bit more logic, but notice how all of the syntax is on a single page:

@{
    var id = Request["ID"];
    var sqlSelect = "select Id, PictureNumber, LastName, FirstName, Grade, HomeSchool, TileLocation,IsNull(DisplayStudentOnline,1) as DisplayStudentOnline,IsNull(FeaturedImage,0) as FeaturedImage,IsNull(FeaturedStatement,0) as FeaturedStatement,Description from ProjectData where PictureNumber=@0";
    var db=Database.Open("Dev");
    var sqlQuery = db.QuerySingle(sqlSelect,id);
    var studentFirstName = sqlQuery.FirstName;
    var studentLastName = sqlQuery.LastName;
    var compassionStatement = sqlQuery.Description;
    var homeSchool = sqlQuery.HomeSchool;
    var tileLocation = sqlQuery.TileLocation;
    var displayOnline = sqlQuery.DisplayStudentOnline;
    var isFeaturedImage = sqlQuery.FeaturedImage;
    var isFeaturedStatement = sqlQuery.FeaturedStatement;
    var pictureID = sqlQuery.PictureNumber;
    var imageUrl = "http://images.appletoncompassion.org/compassionimagesfull/thumb/" + @pictureID + ".jpg";
    var isImageCheck = string.Empty;

    if (isFeaturedImage) {
        isImageCheck = "checked";
    }

    var isStatementCheck = "";

    if (isFeaturedStatement) {
        isStatementCheck = "checked";
    }

    var displayOnlineCheck = "";
    if (displayOnline) {
        displayOnlineCheck = "checked";
    }

    var ischeckedonpost = string.Empty;

    if (IsPost) {
        compassionStatement = Request["statement"];
        tileLocation = Request["tileLoc"]
        displayOnline = ParseCheckBox(Request["displayOnline"]);
        isFeaturedImage = ParseCheckBox(Request["chkFeaturedImage"]);
        isFeaturedStatement = ParseCheckBox(Request["chkFeaturedStatement"]);
        var sqlUpdate = "Update ProjectData set description = @0, TileLocation=@1, DisplayStudentOnline=@2, FeaturedImage=@3,FeaturedStatement=@4 where pictureNumber=@5";
        db.Execute(sqlUpdate,compassionStatement,tileLocation,displayOnline,isFeaturedImage,isFeaturedStatement,pictureID);
        Response.Redirect("Page.cshtml");
    }
}

@functions {

bool ParseCheckBox(string checkBoxValue) {
    Response.Write("Value in: " + checkBoxValue +"</br>");
    bool returnValue = false;

    if (checkBoxValue == "on") {
        returnValue = true;
    }
    else {
        returnValue = false;
    }

    Response.Write("Value out: " + returnValue +"</br>");
    return returnValue;
    }
}

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Edit Artist</title>
</head>
<body>
    <a href="Page.cshtml">Home Page</a>
        <form action="" method="post">
        <p>Picture Number: @pictureID</p>
        <p>First Name: @studentFirstName</p>
        <p>Last Name: @studentLastName</p>
        <p>Home School: @homeSchool</p>
        <p>Tile Location: <input type="text" name="tileLoc" value="@tileLocation"/></p>
        <p>Statement:</p><p> <textarea id="txtStatement" rows="10" columns="20" style="width:600px" name="statement">@compassionStatement</textarea></p>
        <p>Display Student Online <input type="checkbox" name="displayOnline" @displayOnlineCheck/></p>
        <p>Featured Art <input type="checkbox" name="chkFeaturedImage" @isImageCheck/></p>
        <p>Featured Statement<input type="checkbox" name="chkFeaturedStatement" @isStatementCheck/></p>
        <img src="@imageUrl"/>
        <p><input type="submit" value="Save"/></p>
    </form>
</body>
</html>

Why Use it? WebMatrix is Microsoft's response to tools such as Ruby and PHP that generally use inline SQL and allow developers to quickly get sites published. It includes many templates so you can get started quickly, and it will tie into Open Source projects such as Joomla.

I want to learn more! Official WebMatrix Site

WebMatrix Development 101

Web Matrix 101 book - This is a nice little introduction and is only $1 for the Kindle.


 

Mobile Apps Provide the "Finishing Touches" to the Appleton Compassion Project

The Appleton Compassion Projectis a community art project in which all Appleton Area School District students created a 6" x 6" tile depicting their idea of compassion. Each student then wrote a statement about their tile and what compassion means to them. The art and statements can be viewed in the Trout Museum of Art or online at www.appletoncompassion.org. Adding the writing element to the art project has produced some very well rounded, heartfelt depictions of the word "Compassion".

The artist statements range all over the board; from moving, to amusing, to first-grader-cute. It quickly became apparent that with the job of physically displaying over 10,000 pieces of Art on the walls of the Trout Museum of Art, that the compassion statements would not be available for display alongside the tiles. Since the writing element was just as important to the project as the art, we knew we needed to come up with a solution to allow museum visitors to read the statements. The answer? Smartphone apps! Skyline created applications for the three major platforms - Android, iPhone and Windows Phone 7 - that museum visitors can install on their mobile phones so they can view artist statements along with the art.

Since this is the first time that Skyline has created mobile apps for the three major mobile platforms, I thought I'd share how we approached the design of the applications, focusing on what was common between all three. Then, in future blog posts each of the mobile platforms will be discussed from a development standpoint.

In essence, the goal of the mobile application design, at a high level, focused on two things: One, consistency of functionality within three applications, and two, have the application behave like a native application on the individual mobile phones. Okay, what does this really mean? We sat down as a team and identified the functionality the application should have. For the mobile applications these were the features we wanted:

  • Highlight featured art upon entering the app
  • By clicking on an image users would be able to view the compassion statement
  • Search by student name
  • Search by picture number
  • Allow users to mark and keep a list of favorites
  • Have static text to highlight information about the museum, exhibit, hours, Skyline, etc. Once a set of features was decided on, we focused on having those pieces display consistently within the applications, so that featured art was first, favorites was second, and so on. We also wanted to make sure that search was available on each screen across the application. Finally, we attempted to use consistency with the graphics across platforms wherever possible. All of the applications have the same splash screen (featuring Art by Skyline employees) and use the same logo where needed.

Each developer took these requirements and implemented them within the various mobile platforms so they were consistent for the users of that platform. For example, the iPhone and Windows Phone 7 have very different UI implementations. The iPhone has more of a button-driven menu interface, where the Windows Phone UI utilizes text and swiping as a function of their Metro UI. This results in the search button being at the bottom of the screen for the iPhone application and at the top for the Windows Phone application. Each application has the same functionality, just implemented differently - appropriate for the native platform.

The last part of the mobile applications is the data services that feed the application. Surprisingly enough, there are only two. The services are REST-based, with the data returned to the client in XML format.

The first service returns a random set of featured art (http://www.appletoncompassion.org/rest/FeaturedStatements/12). With REST, you can provide parameters in the URL, so in the instance the number tells you how many items to return. We have a single object type we used for both of the services to return, so in this instance there is some excess data in the XML stream that would not necessarily be needed, but it made development easier. This REST call is used to return the featured images that greet the user each time they start the application.

The second service is responsible for searching. Within the application, there are two types of search. The first one is by picture number, so if you are at the exhibit in the museum you can type in a number and see the artist statement that corresponds with the tile. The second is by name, so you can look up a specific child. We were able to implement this search functionality in a single service call, by having the back end service worry about if the search was a number only or if it had text. The service can search by number (http://www.appletoncompassion.org/rest/search/7158), last name (http://www.appletoncompassion.org/rest/search/ptacek) or full name (http://www.appletoncompassion.org/rest/search/nora%20ptacek).

It's a small example, but it illustrates the point of trying to encapsulate as much logic is possible in our service calls and not put the burden on the mobile phone. This way if there's a bug or change that needs to be made in the search functionality, we can update the service call, and not have to go through the lengthy process of updating three mobile applications in their respective mobile stores.

Watch for future blog posts that discuss each individual platform in more detail.


 

John Ptacek I'm John Ptacek, a software developer for Skyline Technologies. This blog is my contains my content and opinionss, which are not those of my employer.

Currently, I am reading The Dark Forest by Cixin Liu (刘慈欣)

@jptacekGitHubLinkedInStack Overflow