crli
Jan 19, 2010
  6576
(1 votes)

Quick intro to ASP.NET MVC for the WebForm developer

To prepare for future discussions around dashboard gadgets I thought it was a good idea to introduce the ASP.NET MVC framework.

The main buidling blocks of the ASP.NET MVC framework is routing, controllers, views and the model support. There are also multiple hooks in and around these blocks to bend the behaviour to your wim.

Routes

Routes are registered to handle an incoming URL pattern and map it to your code along with parameters, and back from parameters to an URL.  A route registration typically is a piece of code in Application_Start that may look like this:

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

This will register a route that accepts anything from 0 to 3 segments and matches each segments to the corresponding parameter or the default.

E.g. URL = "/hello/world/1" is matched to controller = "hello", action = "world" and id = "1"

The default parameters mean that the URL = "/" would be matched to controller = "Home", action = "Index" and id = ""

Such routes can be configured to handle a lot of scenarios and more. Keep in mind that routes are organized in a table which is evaluated from fist to last, the first to match is used.

Controllers

This is the handler for a piece of functionality. By way of routing a method is invoked in which you decide what action to take. The action may be rendering one view or another, redirecting to somewhere else, or returning a JSON string that is easily interpreted on the client.

A controller may look like this:

public class HomeController : Controller
{
public ActionResult Index() { return View(); } }

This is a controller that given the route above responds to everything from "/" to "/home/index/whatever". An interesting aspect of route parameters that they are used to call the action method, e.g.:

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

This will convert the {id} parameters into an integer or throw an exception if this isn't possible. Also the query string, and form values are also fitted into the method arguments when possible. The view model may be any kind class (e.g. a list of persons or an address object) and it's used on the view to render HTML. Very worth mentioninng is that the controller logic is (unit) testable.

Views

By default views are ASPX pages inheriting from a base class that provides useful properties. Rather than using the control hierarchy and the page lifecycle to construct the interface plain html and extension methods (html helpers) are preferred. A fundamental difference is that controls needn't reconstruct their state on postback. Instead, plain old HTTP POST/GETs target a controller action and posted data doesn't pass through a server control.

E.g. WebForms:
<asp:TextBox ID="Name" runat="server" />

MVC:
<%= Html.TextBox("Name") %>

One of the appealing aspects of this model is that AJAX interaction becomes very easy as the HTML can live on the client and interact with a controller without the need to keep the server control model up to date.

Model

The model are simply classes that reflect the problem the application tries to solve. These classes can be used and tested separately from the presentation. ASP.NET MVC doesn't propose any particular database tooling. Most of the time you would use an O/R mapper to get a class instance, update it and pass it along to a view. What the framework will do is to give a lot of support in updating, and working with any class within controllers and views.

E.g. consider the following actions:

public ActionResult Index()
{
  return View(new Person { Name = "Fill me up scotty" });
} 
public ActionResult Update(Person person)
{
  Store.Save(person);
  View("Index", person);
} 

And this view code:

<% using(Html.BeginForm("Update", "Home")) { %>

<%= Html.TextBox("Name") %>
<
input type="submit" /> <% } %>

Not only will the MVC framework popuplate the input box with the name of the person. It will also repopuplate a person object in the Update method when the form is posted. Other nice features include validation support, the possibility to post to any action on any controller and an abundance of options that might better fit your fancy.

Summary and some pitfalls

As you may have noticed this model brings you much closer to the web. While MVC does a lot of handholding a web application developer is faced with other responsibilities and options. Anyone without a strong investment in web forms will probably find themselves at home.

A controller doesn’t have a specific URL. This is the concern of a route.

The web control developer entering this world will probably start looking for new forms of code reuse.

Jan 19, 2010

Comments

Please login to comment.
Latest blogs
Copy Optimizely SaaS CMS Settings to ENV Format Via Bookmarklet

Do you work with multiple Optimizely SaaS CMS instances? Use a bookmarklet to automatically copy them to your clipboard, ready to paste into your e...

Daniel Isaacs | Dec 22, 2024 | Syndicated blog

Increase timeout for long running SQL queries using SQL addon

Learn how to increase the timeout for long running SQL queries using the SQL addon.

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Overriding the help text for the Name property in Optimizely CMS

I recently received a question about how to override the Help text for the built-in Name property in Optimizely CMS, so I decided to document my...

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Resize Images on the Fly with Optimizely DXP's New CDN Feature

With the latest release, you can now resize images on demand using the Content Delivery Network (CDN). This means no more storing multiple versions...

Satata Satez | Dec 19, 2024

Simplify Optimizely CMS Configuration with JSON Schema

Optimizely CMS is a powerful and versatile platform for content management, offering extensive configuration options that allow developers to...

Hieu Nguyen | Dec 19, 2024

Useful Optimizely CMS Web Components

A list of useful Optimizely CMS components that can be used in add-ons.

Bartosz Sekula | Dec 18, 2024 | Syndicated blog