crli
Jan 19, 2010
  5929
(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
Preview multiple Visitor Groups directly while browsing your Optimizely site

Visitor groups are great - it's an easy way to add personalization towards market segments to your site. But it does come with it's own set of...

Allan Thraen | Sep 26, 2022 | Syndicated blog

The Report Center is finally back in Optimizely CMS 12

With Episerver.CMS.UI 12.12.0 the Report Center is finally re-introduced in the core product.

Tomas Hensrud Gulla | Sep 26, 2022 | Syndicated blog

Dynamic Route in ASP.NET Core When MapDynamicControllerRoute Does Not Work

Background Creating one of the add-on for Optimizely I had to deal with challenge to register dynamically route for the API controller. Dynamic rou...

valdis | Sep 25, 2022 | Syndicated blog

404 Error on Static Assets Within an Optimizely plugin

Background With the move to CMS 12 and .NET 5/6, developers are now able to build Plugins and Extensions using Razor Class Libraries (RCL).  These...

Mark Stott | Sep 23, 2022