# Getting Started
Castle MonoRail greatly simplifies web development. The Getting Started chapter is going to show you how common tasks are handled and how MonoRail performs most of the repetitive work in web development on your behalf.
Among other things you will learn:
* About controllers and views and how they relate to each other
* How to use layouts and rescues
* How to use the `SmartDispatcherController` and the data binder
* How to easily create a CRUD page
* How Castle ActiveRecord integrates nicely with MonoRail
Although it should go without saying, you are not obliged to use ActiveRecord as your primary data access framework with MonoRail - you can use whatever approach to performing data access you like. That being said if you do use ActiveRecord, there are some provided integrations that might save you some time. Regardless, the framework provided allows you to develop similar integration for your preferred data access approach should you choose to do so.
## Requirements
Before beginning you will need a copy of the MonoRail binaries and dependencies on your local machine to use in your project; the latest versions can be obtained from the Castle [downloads page](http://www.castleproject.org/).
Also, during the course of this chapter will be using a database. For simplicity's sake all discussion surrounding database configuration will refer to MSSQL Server 2000 however if you prefer to use another database you can select any other database supported by NHibernate and will find very little deviation from the text in this chapter.
## Creating the Project Skeleton
As mentioned in the [Introduction](introduction.md), MonoRail tends to favour convention over configuration and when creating a project structure we encourage you to use a project structure similar to the following to remain in line with these conventions.

You are by no means _required_ to follow these conventions, however they will most likely made development easier for you in the long run. The following sections show you how to create this structure manually or by using the MonoRail project wizard and will further explain the reasoning behind its use.
### Create the project
Create an `ASP.NET Web Application` project in Visual Studio. Name the new project `GettingStartedSample` then click the OK button.
### Reference the MonoRail Assemblies
To make the new project into a MonoRail application you will need to add references to the MonoRail assemblies. For the purposes of our sample application the assemblies listed below will be required.
Assembly | Description
---------|------------
`Castle.MonoRail.Framework.dll` | Contains the classes that make up the core of the MonoRail framework.
`Castle.MonoRail.Framework.Views.NVelocity.dll` | Defines an NVelocity view engine plugin that will be used for handling views. This will in turn use the NVelocity rendering engine.
`Castle.Components.Validator.dll` | Provides a lightweight validation infrastructure created by Castle.
`Castle.Components.Binder.dll` | Contains the logic for the databinding that is used in MonoRail.
`Castle.Components.Common.EmailSender.dll` | Defines the interface for components that send email.
`Castle.Components.Common.EmailSender.SmtpEmailSender.dll` | Provides an SMTP implementation of the EmailSender that will be responsible for sending email.
`Castle.Core.dll` | Core Castle class library containing functionality used by many projects, including MonoRail.
`NVelocity.dll` | The NVelocity template engine used for rendering NVelocity templates.
### Create the Project Folders
The next step is to create the following folders on the project. Again, this is just a convention we encourage you to follow - you may come up with a more suitable convention for your projects after you get used to the framework so this is no way mandatory.

### Configuration
To configure the application additional information needs to be added to the web.config file; you must register the MonoRail configuration handler, the MonoRail configuration section, an HTTP handler and an HTTP module. Each of these will be discussed further below.
First, add the MonoRail configuration handler:
```xml
Hello world from my first action.
``` **Editing .vm files:** You can make Visual Studio use the HTML editor for .vm files. Use the Open With... option from the context menu. This is a fairly simple view; note that in the template we did not include the html or body tags. This is because we will leave those to the layout to render, which we will cover next. ### Setting the Layout and Rescue When we created the `HomeController` you may have noticed the `Layout` and `Rescue` attributes were specified on the class. ```csharp [Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController ``` These attributes define the following: * The `Layout` attribute indicates that every view rendered by this controller to should be wrapped in the content from the `default.vm` template in the `/layouts` folder of the project. * The `Rescue` attribute tells MonoRail that if any unhandled exception is thrown by an action on the `HomeController` a special _rescue_ view template called `generalerror.vm` in the `/rescues` folder of the project should be rendered. Layouts and rescues can minimize the amount of work you do when building view templates and allow your view templates to be better encapsulated. ### Creating the Layout A _layout_ defines the outer content of a rendered view and has some similarities to a master page. Your project can have as many layouts as you like - the layout files simply need to be placed into the /layouts folder of the project. Our first layout is very simple, and should be saved as `default.vm` on the `/layouts` folder. ```htmlThis is the rescue page. See the exception details below
#set($exception = $context.LastException) #showexception($exception)``` There's quite a bit of logic in this template, but we won't get into the details now. If you want to explore these features in more detail see the NVelocity documentation. Now let's create a new action that will throw an exception so we can see the rescue template in action: ```csharp [Layout("default"), Rescue("generalerror")] public class HomeController : SmartDispatcherController { public void Index() { } public void ErroneousAction() { throw new Exception("I'm a bad bad action."); } public void DataToTheView() { PropertyBag["name"] = "John Doe"; PropertyBag["today"] = DateTime.Now; RenderView("data"); } } ``` If you now run the application and go to `home/erroneousaction.rails` in your browser the `ErroneousAction` method will throw an exception as we specified and the rescue will be displayed. ## Data Binding Although the controller we've been using so far in our sample application extends from `SmartDispatcherController` we haven't yet used any of its more advanced capabilities. The SmartDispatcherController base class, as the name implies, provides some "smart" functionality, including binding query string values, form values and even cookies to the parameters of action methods when they are invoked. This includes both simple types and custom, complex types as will be discussed in the following sections. ### Simple Parameters Simple types can be bound to action parameters with no special configuration other than to ensure your controller is derived from the SmartDispatchController class. For example, suppose you have the following HTML form on a view: ```html ``` The form action directs the post to the `HomeController` class' `SaveInformation` action method. This method can be constructed in such a way that it will expect the values from the submitted HTML form as parameters: ```csharp public class HomeController : SmartDispatcherController { public void Index() { } public void SaveInformation(String name, int age, DateTime dob) { // work work work // Send the user back to the index RedirectToAction("index"); } } ``` In the above example each of the form fields will be data-bound to the method parameter of the same name on the `SaveInformation` method. Using this automatic data binding feature reduces the effort required to access the values submitted by the view. It is still possible to access the values from the HTML form without data binding through use of the `Params` or `Form` name-value collections exposed by the controller, however using data binding is cleaner and simpler. The code sample below provides the same functionality as the example above - we will leave it to you to decide which is clearer and easier to use. ```csharp public class HomeController : SmartDispatcherController { public void Index() { } public void SaveInformation() { string name = Params["name"]; int age = Convert.ToInt32(Params["age"]); DateTime dob = Convert.ToDateTime(Params["dob"]); // work work work // Send the user back to the index RedirectToAction("index"); } } ``` The `SmartDispatchController` is capable of handling a wide range of built-in .NET types. For further details on the types supported refer to the documentation on Data Binding in the Controllers chapter. ### Complex Objects Along with data binding simple value types the `SmartDispatcherController` provides features to data bind custom and arbitrarily complex objects. In order to illustrate how this can be achieved we will create a new controller that presents a contact form designed to allow a user to contact a department in a fictitious company. First, create a new controller named `ContactController` and add two empty actions; `ContactForm` and `SendContactMessage`: ```csharp namespace GettingStartedSample.Controllers { using System; using Castle.MonoRail.Framework; [Layout("default"), Rescue("generalerror")] public class ContactController : SmartDispatcherController { public void ContactForm() { } public void SendContactMessage() { } } } ``` Next, in the `/models` folder create a class named `Contact` - this class will be used to represent the contact information submitted by the user. ```csharp public class Contact { private string from; private string area; private string subject; private string message; public string From { get { return from; } set { from = value; } } public string Area { get { return area; } set { area = value; } } public string Subject { get { return subject; } set { subject = value; } } public string Message { get { return message; } set { message = value; } } } ``` Now create the view to be displayed by the `ContactForm` action. The template file `contactform.vm` should be created in the `\views\contact` folder and must contain the following code: ```html
We are interested in hearing from you.
``` In the code above we have made use of the FormHelper helper class to generate an HTML form with the following source: ```htmlWe are interested in hearing from you.
``` **Further FormHelper information:** Further information on the `FormHelper` helper and on helpers in general can be found in the chapter entitled Helpers. At this point it is important to note that the name of each generated field on the HTML form has been prefixed with the text `contact` followed by a dot and then the name of the property of the form (eg. `contact.from` in the case of the "`From`" field in our example). This indicates that each of the fields belong to a single group of data that will be bound to an object by the data binder. Finally, change the parameters of the `SendContactMessage` action on the `ContactController` to indicate to the MonoRail binder that it should bind the form data prefixed with `contact` to the `Contact` class created earlier: ```csharp public void SendContactMessage([DataBind("contact")] Contact theContact) { // Pretend to save the contact ... // ..work work work.. // Now lets add the contact to the property bag // so we can render a nice message back to the user PropertyBag["contact"] = theContact; RenderView("confirmation"); } ``` As you can see, a parameter named `theContact` has been added to the `SendContactMethod` action which has been decorated with the `DataBindAttribute`. The `DataBindAttribute` has been initialized with a string parameter that tells the binder that it should attempt bind the form values prefixed with "`contact.`" to the properties of the `theContact` parameter that share the same name as the part of the form element name that appears after the text "`contact.`". While we're here we might as well create the confirmation view as well: ```htmlThanks $!contact.from, we have received your message and will get back to your shortly.
``` Now if you visit `/contact/contactform.castle` in your browser you should be able to view the results of your work. Fill the form elements, submit it and you should see the name you submitted in the from field on the form.   ## See Also ### Integrating with ActiveRecord In addition to this getting started guide you may want to look at [Getting Started with ActiveRecord Integration](getting-started-with-activerecord-integration.md) for a slightly more advanced getting started topic introducing data persistence with [ActiveRecord](https://github.com/castleproject/ActiveRecord).