DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Getting Started with ASP.NET MVC 1.0
refcard cover
Refcard #069

Getting Started with ASP.NET MVC 1.0

Setting Up An Environment and Creating a Web Application

Explains how to setup your environment to work with ASP.NET MVC and how to create an ASP.NET MVC Web application

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Simone Chiaretta
Software Architect, Avanade
author avatar Keyvan Nayyeri
Ph.D. Student, UTSA
Table of Contents
► Introduction ► Prerequisites ► Installation ► The MVC pattern ► Build your first application ► The Fundame ntals of ASP.NET MVC ► Routing ► Model ► Controller ► Action Method ► Model Binder ► View ► HTML helper ► T4 Templates ► Ajax
Section 1

Introduction

By Simone Chiaretta and Keyvan Nayyeri

ASP.NET MVC is a new framework for building Web applications developed by Microsoft; it was found that the traditional WebForm abstraction, designed in 2000 to bring a “desktop-like” development experience to the Web, was sometimes getting in the way, and could not provide proper separation of concerns, so it was difficult to test. Therefore a new, alternative framework was built in order to address the changing requirements of developers. It was built with testability, extensibility and freedom in mind.

This Refcard will first explain how to setup your environment to work with ASP.NET MVC and how to create an ASP.NET MVC Web application. Then it will go deeper in details explaining the various components of the framework and showing the structure of the main API. Finally, it will show a sample of standard operation that developers can do with ASP.NET MVC.

Section 2

Prerequisites

The ASP.NET MVC is a new framework, but it’s based on ASP.NET core API: in order to understand and use it, you have to know the basic concepts of ASP.NET. Furthermore, since it doesn’t abstract away the “Web” as the traditional WebForm paradigm does, you have to know HTML, CSS and JavaScript in order to take full advantage of the framework.

Section 3

Installation

To develop a Web site with ASP.NET MVC, all you need is Visual Studio 2008 and the .NET Framework 3.5 SP1. If you are an hobbyist developer you can use Visual Web Developer 2008 Express Edition, which can be downloaded for free at the URL: http://www.microsoft.com/express/vwd/.

You also need to install the ASP.NET MVC library, which can be downloaded from the official ASP.NET Web site at http://www.asp.net/mvc/download.

You can also download everything you need, the IDE, the library, and also a free version of SQL Server (Express Edition) through the Web Platform Installer, available at: http://www.microsoft.com/web/.

Section 4

The MVC pattern

As you probably have already guessed from the name, the framework implements the Model View Controller (MVC) pattern.

MVCpattern

The UI layer of an application is made up of 3 components:

MVC ComponentDescriptionModelThe component responsible for data interactions with data storage system (typically a database) and main business logic implementations.ViewThe component responsible for displaying data passed from Controller to it which also renders the user interface of the site.ControllerThe component that acts like a bridge between the model and the view to load data based on the request and pass them to view, or pass the data input by user to the model.

And the flow of an operation is depicted in the diagram:

  1. The request hits the Controller.
  2. The Controller delegates the execution of “main” operation to the Model.
  3. The Model sends the results back to the Controller.
  4. The Controller formats the data and sends them to the View.
  5. The View takes the data, renders the HTML page, and sends it to the browser that requested it.
Section 5

Build your first application

Starting the developing of an ASP.NET MVC application is easy. From Visual Studio just use the "File > New Project" menu

Command, and select the ASP.NET MVC Project template (as shown in the following figure).

MVCProject_template

Type in the name of the project and press the "OK" button. It will ask you whether you want to create a test project (I suggest choosing Yes), then it will automatically create a stub ASP.NET MVC Web site with the correct folder structure that you can later customize for your needs.

folder_structure

As you can see, the components of the applications are wellseparated in different folders.

Folder NameContains/ContentStatic contents for your site, like CSS and images/ControllersAll the Controllers of the application, one per file/ModelsThe classes that encapsulate the interaction with the Model/ScriptsThe JavaScript files used by your application (by default it contains jQuery/ViewsAll the views of the application, in sub-folders that are related one to one with the controllers

Section 6

The Fundame ntals of ASP.NET MVC

One of the main design principles of ASP.NET MVC is “convention over configuration”, which allows components to fit nicely together based on their naming conventions and location inside the project structure.

The following diagram shows how all the pieces of an ASP.NET MVC application fit together based on their naming conventions:

MVCnaming

Section 7

Routing

The routing engine is not part of the ASP.NET MVC framework, but is a general component introduced with .NET 3.5 SP1. It is the component that is first hit by a request coming from the browser. Its purpose is to route all incoming requests to the correct handler and to extrapolate from the URL a set of data that will be used by the handler (which, in the case of an ASP.NET MVC Web application, is always the MvcHandler) to respond to the request.

routing_engine

To accomplish its task, the routing engine must be configured with rules that tell it how to parse the URL and how to get data out of it. This configuration is specified inside the RegisterRoutes method of the Global.asax file, which is in the root of the ASP.NET MVC Web application.

​x
1
​
2
public static void RegisterRoutes(RouteCollection routes)
3
{
4
routes.MapRoute(
5
“Default”, //Route Name
6
“{controller}/{action}/{id}”, //Route Formats
7
new { controller = “Home”, action = “Index”, id = “” } //Defaults
8
);
9
}       
10
​

The snippet above shows the default mapping rule for each ASP.NET MVC application: every URL is mapped to this route, and the first 3 parts are used to create the data dictionary sent to the handler. The last parameter contains the default values that must be used if some of the URL tokens cannot be populated. This is required because, based on the default convention, the data dictionary sent to the MvcHandler must always contain the controller and the action keys.

Examples of other possible route rules:

URLRuleData Dictionary/Posts/Show/5

6
1
​
2
Format: “{controller}/
3
{action}/{id}”
4
Default: new { controller
5
= “Home”, action = “Index”,
6
id = “” }

Controller = Posts Action = Show Id = 5/archive/2009-10-02/MyPost

4
1
​
2
Format: /archive/{date}/{title}
3
Default: { controller = “Posts”, action
4
= “show”}
5
1
​
2
Controller = Posts
3
Action = Show
4
Date = 2009-10-02
5
Title = My post
Section 8

Model

ASP.NET MVC, unlike other MVC-based frameworks like Ruby on Rails (RoR), doesn’t enforce a convention for the Model. So in this framework the Model is just the name of the folder where you are supposed to place all the classes and objects used to interact with the Business Logic and the Data Access Layer. It can be whatever you prefer it to be: proxies for Web services, ADO.NET Entity Framework, NHibernate, or anything that returns the data you have to render through the views.

Section 9

Controller

The controller is the first component of the MVC pattern that comes into action. A controller is simply a class that inherits from the Controller base class whose name is the name of a controller and ends with “Controller,” and is located in the Controllers folder of the application folder structure. Using that naming convention, the framework automatically calls the specified controller based on the parameter extrapolated by the URL.

9
1
​
2
namespace MyMvcApp.Controllers
3
{
4
        public class PageController : Controller
5
        {
6
           //Controller contents.
7
        }
8
}       
9
​

The real work, however, is not done by the class itself, but by the method that lives inside it. These are called Action Methods.

Section 10

Action Method

An action method is nothing but a public method inside a Controller class. It usually returns a result of type ActionResult and accepts an arbitrary number of parameters that contain the data retrieved from the HTTP request. Here is what an action method looks like:

8
1
​
2
public ActionResult Show(int id)
3
{
4
        //Do stuff
5
        ViewData[“myKey”]=myValue;
6
        return View();
7
}       
8
​

The ViewData is a hash-table that is used to store the variables that need to be rendered by the view: this object is automatically passed to the view through the ActionResult object that is returned by the action. Alternatively, you can create your own view model, and supply it to the view.

public ActionResult Show(int id)

6
1
​
2
{
3
  //Do stuff
4
  return View(myValue);
5
}
6
​

This second approach is better because it allows you to work with strongly-typed classes instead of hash-tables indexed with string values. This brings compile-time error checking and Intellisense.

Once you have populated the ViewData or your own custom view model with the data needed, you have to instruct the framework on how to send the response back to the client. This is done with the return value of the action, which is an object that is a subclass of ActionResult. There are various types of ActionResult, each with its specific way to return it from the action.

ActionResult TypeMethodPurposeViewResultView()Renders a view whose path is inferred by the current controller and action: /View/controllerName/ ActionName.aspxViewResultView(viewName)

5
1
​
2
Renders a view whose name is
3
specified by the parameter:
4
/View/controllerName/
5
viewName.aspx

ViewResultView(model)Renders the view using the default path, also passing a custom View Model that contains the data that needs to be rendered by the view.PartialViewResultPartialView()Same as View, but doesn’t return a complete HTML page, only a portion of it. Looks for the file at following the path: /View/controllerName/ ActionName.ascxPartialViewResultPartialView(viewName)Renders a partial view whose name is specified by the parameter: /View/controllerName/ viewName.ascxPartialViewResultPartialView(model)Renders a partial view using the default path, also passing a custom View Model that contains the data that needs to be rendered by the partial view.RedirectResultRedirect(url)Redirects the client to the URL specified.RedirectToRouteResultRedirectToAction(actionName)Redirects the client to the action specified. Optionally you can specify also the controller name and an additional list of parameters.RedirectToRouteResultRedirectToRRedirects the client to the route specified. Optionally you can specify an additional list of parameters.ContentResultContent(content)Sends to the content specified directly to the client. Optionally you can specify the content type and encoding.JsonResultJson(data)Serializes the data supplied in Json format and sends the Json string to the client.FileResultFile(filename,contenttype)Sends the specified file directly to the client. Optionally you can provide a stream or a byte array instead of a physical path.JavaScriptResultJavaScript(javascript)Sends the script provided as external JavaScript file.EmptyResultnew EmptyResult()Doesn’t do anything: use this in case you handle the result directly inside the action (not recommended).

Section 11

Model Binder

Using the ActionResults and the ViewData object (or your custom view model), you can pass data from the Action to the view. But how can you pass data from the view (or from the URL) to the Action? This is done through the ModelBinder. It is a component that retrieves values from the request (URL parameters, query string parameters, and form fields) and converts them to action method parameters.

As everything in ASP.NET MVC, it’s driven by conventions: if the action takes an input parameter named Title, the default Model Binder will look for a variable named Title in the URL parameters, in the query string, and among the values supplied as form fields.

model_binder

But the Model Binder works not only with simple values (string and numbers), but also with composite types, like your own objects (for example the ubiquitous User object). In this scenario, when the Model Binder sees that an object is composed by other sub-objects, it looks for variables whose name matches the name of the properties of the custom type. Here it’s worth taking a look at a diagram to make things clear:

model_binder_diagram

Section 12

View

The next and last component is the view. When using the default ViewEngine (which is the WebFormViewEngine) a view is just an aspx file without code-behind and with a different base class.

Views that are going to render data passed only through the ViewData dictionary have to start with the following Page directive:

5
1
​
2
<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
3
Inherits=”System.Web.Mvc.ViewPage” %>
4
​
5
​

If the view is also going to render the data that has been passed via the custom view model, the Page directive is a bit different, and it also specifies the type of the view model:

4
1
​
2
<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
3
Inherits=”System.Web.Mvc.ViewPage<PageViewModel>” %>
4
​

You might have noticed that, as with all normal aspx files, you can include a view inside a master page. But unlike traditional Web forms, you cannot use user controls to write your HTML markup: you have to write everything manually. However, this is not entirely true: the framework comes with a set of helper methods to assist with the process of writing HTML markup. You’ll see more in the next section.

Hot Tip

Another thing you have to handle by yourself is the state of the application: there is no ViewState and no Postback.

Section 13

HTML helper

You probably don’t want to go back writing the HTML manually, and neither does Microsoft want you to do it. Not only to help you write HTML markup, but also to help you easily bind the data passed from the controller to the view, the ASP.NET MVC Framework comes with a set of helper methods collectively called HtmlHelpers. They are all methods attached to the Html property of the ViewPage. For example, if you want to write the HTML markup for a textbox you just need to write:

3
1
​
2
<%= Html.Textbox(“propertyName”)%>
3
​

And this renders an HTML input text tag, and uses the value of the specified property as the value of the textbox. When looking for the value to write in the textbox, the helper takes into account both the possibilities for sending data to a view: it first looks inside the ViewData hash-table for a key with the name specified, and then looks inside the custom view model, for a property with the given name. This way you don’t have to bother assigning values to input fields, and this can be a big productivity boost, especially if you have big views with many fields.

Let’s see the HtmlHelpers that you can use in your views:

HelperPurpose

3
1
​
2
Html.ActionLink(text,
3
actionName, …)

Renders a HTML link with the text specified, pointing to the URL that represents the action and the other optional parameters specified (controller and parameters). If no optional parameters are specified, the link will point to the specified action in the current controller.

3
1
​
2
Html.RouteLink(text,
3
routeValues, …)

Renders a HTML link as the method ActionLink, but now using the route values, and optionally the route name, as input.Html.BeginForm(actionName,…)Renders the beginning HTML form tag, setting as action of the form the URL of the action specified. The URL creation works exactly the same as the ActionLink method.Html.EndForm()Renders the form closing tag.Html.Textbox(name)Renders a form input text box, populating it with the value retrieved from the ViewData or custom view model object. Optionally you can specify a different value for the field, or specify additional HTML attributes.Html.TextArea(name, rows, cols, …)Same as Textbox, but renders a textarea, of the specified row and column size.Html.Checkbox(name)Renders a checkbox.Html.RadioButton(name, value)Renders a radio button with the given name, the given value and optionally specifying the checked state.Html.Hidden(name)Renders a form input field of type hidden.

3
1
​
2
Html.DropDownList(name,
3
selectList,…)

Renders a select HTML element, reading the options from the selectList variable, which is a list of name-value pairs.

3
1
​
2
Html.ListBox(name,
3
selectList,…)

Same as the DropDownList method, but enables the ability to select multiple options.

3
1
​
2
Html.
3
ValidationMessage(modelName, …)

Displays a validation message if the specified field contains an error (handled via the ModelState).Html.ValidationSummary(…)Displays the summary with all the validation messages of the view.

3
1
​
2
Html.
3
RenderPartial(partialViewName)

Renders on the view the contents of the specified partial view.

As alternative to writing Html.BeginForm and Html.CloseForm methods, you can write an HTML form by including all its elements inside a using block:

5
1
​
2
<% using(Html.BeginForm(“Save”)) { %>
3
<!—all form elements here -->
4
<% } %>
5
​

To give you a better idea of how a view that includes an editing form looks like, here is a sample of a complete view for editing an address book element:

12
1
​
2
<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
3
Inherits=”System.Web.Mvc.ViewPage<EditContactViewModel>” %>
4
<% using(Html.BeginForm(“Save”)) { %>
5
Name: <%= Html.Textbox(“Name”) %> <br/>
6
Surname: <%= Html.Textbox(“Surname”) %> <br/>
7
Email: <%= Html.Textbox(“Email”) %> <br/>
8
Note: <%= Html.TextArea(“Notes”, 80, 7, null) %> <br/>
9
Private <%= Html.Checkbox(“IsPrivate”) %><<br/>
10
<input type=”submit” value=”Save”>
11
<% } %>
12
​
Section 14

T4 Templates

But there is more: bundled with Visual Studio there is a template engine (made T4 as in Text Template Transformation Toolkit) that helps automatically generate the HTML of your views based on the ViewModel that you want to pass to the view.

The “Add View” dialog allows you to choose with which template and based on which class you want the views to be generated

Template NamePurposeCreateGenerates a form to create a new instance of the item you selectedDetailsGenerates a view that shows all the properties of the item you selectedEditGenerates a form to edit a instance of the item you selectedEmptyGenerates an empty view, only with the declaration of the class it’s based onListGenerates a view with a list of the items you selected

Add View dialog

What these templates do is mainly iterating over all the properties of the ViewModel class and generating the same code you would have probably written yourself, using the HtmlHelper methods for the input fields and the validation messages.

For example, if you have a view model class with two properties, Title and Description, and you choose the Edit template, the resulting view will be:

9
1
​
2
<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.
3
Master”
4
Inherits=”System.Web.Mvc.ViewPage<IssueTracking.Models.Issue>” %>
5
<asp:Content ID=”Content1” ContentPlaceHolderID=”TitleContent”
6
runat=”server”>
7
        Edit
8
</asp:Content>
9
​
30
1
​
2
<asp:Content ID=”Content2” ContentPlaceHolderID=”MainContent”
3
runat=”server”>
4
  <h2>Edit</h2>
5
  <%= Html.ValidationSummary(“Edit was unsuccessful. Please correct
6
the errors and try again.”) %>
7
  <% using (Html.BeginForm()) {%>
8
    <fieldset>
9
       <legend>Fields<</legend>
10
       <p>
11
                <label for=”Title”>Title:</label>
12
                        <%= Html.TextBox(“Title”, Model.Title) %>
13
                    <%= Html.ValidationMessage(“Title”, “*”) %>
14
           </p>
15
           <p>
16
                        <label for=”Description”>Description:</label>
17
                        <%= Html.TextArea(“Description”,
18
                            Model.Description,7,50,null)%>
19
            <%= Html.ValidationMessage(“Description”, “*”) %>
20
           </p>
21
            <p>
22
            <input type=”submit” value=”Save” />
23
       </p>
24
   </fieldset>
25
<% } %>
26
  <div>
27
       <%=Html.ActionLink(“Back to List”, “Index”) %>
28
  </div>
29
</asp:Content>
30
​
Section 15

Ajax

The last part of ASP.NET MVC that is important to understand is AJAX. But it’s also one of the easiest aspects of the framework.

First, you have to include the script references at the top of the page where you want to enable AJAX (or in a master page if you want to enable itfor the whole site):

4
1
​
2
<script src=”/Scripts/MicrosoftAjax.js” type=”text/javascript”><script>
3
<script src=”/Scripts/MicrosoftMvcAjax.js” type=”text/javascript”></script>
4
​

And then you can use the only 2 methods available in the AjaxHelper: ActionLink and BeginForm.

They do the exact same thing as their HtmlHelper counterpart, just asynchronously and without reloading the page. To make the AJAX features possible, a new parameter is added to configure how the request and the result should be handled. It’s called AjaxOptions and is a class with the following properties:

Parameter NamePurposeUpdateTargetIdThe id of the html element that will be updatedInsertionModeWhere the new content will be inserted:

  • Replace: new content will replace old one
  • InsertAfter: new content will be placed after the current one
  • InsertBefore: new content will be placed before

ConfirmThe question that will be asked to the user to confirm their will to proceedOnBeginGenerates an empty view, only with the declaration of the class it’s based onOnSuccessGenerates a view with a list of the items you selectedOnFailureName of the JavaScript function to be called before the request startsOnCompleteName of the JavaScript function to be called when the request is complete, either with a success or a failureUrlThe URL to sent the request to, if you want to override the URL calculated via the usual actionName and controllerName parametersLoadingElementIdThe id of the HTML element that will be made visible during the execution of the request

For example, here is a short snippet of code that shows how to update a list of items using the AJAX flavor of the BeginForm method:

15
1
​
2
<ul id=”types”>
3
<% foreach (var item in Model) { %>
4
  <li><%= item.Name %></li>
5
<% } %>
6
</ul>
7
<% using(Ajax.BeginForm(“Add”,”IssueTypes”,new AjaxOptions() {
8
    InsertionMode = InsertionMode.InsertAfter,
9
    UpdateTargetId = “types”,
10
    OnSuccess = “myJsFunc”
11
  })) { %>
12
Type Name: <%= Html.TextBox(“Name”) %>
13
<input type=”submit” value=”Add type” />
14
<% } %>
15
​

The AJAX call will be sent to the Add action inside the IssueType controller. Once the request is successful, the result sent by the controller will be added after all the list items that are inside the types element. And then the myJsFunc will be executed.

But what the ASP.MVC library does is just enabling these two methods: if you want more complex interactions you have to use either the AJAX in ASP.NET library or you can use jQuery, which ships as part of the ASP.NET MVC library.

If you want to use the AJAX in ASP.NET library, you don’t have to do anything because you already referenced it in order to use the BeginForm method, but if you want to use jQuery, you have to reference it as well.

3
1
​
2
<script src=”/Scripts/jquery-1.3.2.js” type=”text/javascript”></script>
3
​

One benefit of having the jQuery library as part of the ASP.NET MVC project template is that you gain full Intellisense support. But there is an extra step to enable it: you have to reference the jQuery script both with the absolute URL (as above) needed by the application and with a relative URL, which is needed by the Intellisense resolution engine. So, at the end, if you want to use jQuery and enable Intellisense on it, you have to add the following snippet:

8
1
​
2
<script src=”/Scripts/jquery-1.3.2.js” type=”text/javascript”>
3
</script>
4
<% if(false> { %>
5
<script src=”../../Scripts/jquery-1.3.2.js” type=”text javascript”>
6
</script>
7
<% } %>
8
​

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

ASP.NET Web API: Benefits and Why to Choose It
related article thumbnail

DZone Article

How to Develop a RESTful Web Service in ASP.NET Web API
related article thumbnail

DZone Article

How to Configure and Customize the Go SDK for Azure Cosmos DB
related article thumbnail

DZone Article

Testing SingleStore's MCP Server
related refcard thumbnail

Free DZone Refcard

Getting Started With Low-Code Development
related refcard thumbnail

Free DZone Refcard

JavaScript Test Automation Frameworks
related refcard thumbnail

Free DZone Refcard

Salesforce Application Design
related refcard thumbnail

Free DZone Refcard

E-Commerce Development Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: