Data validation

Contents:

  1. Introduction
  2. Adding validation errors directly to the ModelState
  3. Applying validation attributes
  4. Implementing model validation with IDataErrorInfo
  5. Implementing model validation with IValidatableObject
  6. Implementing client side validation
  7. Implementing remote validation
  8. Summary

1. Introduction

This is the second post in a series of articles about ASP.NET MVC 4. In this post I will use the previous demo application as the starting point and add data validation to the contact us form. You can download the source code for the previous post from Codeplex.

There are several ways to implement validation:

  1. Adding validation errors directly to the ModelState – in this case the validation happens in the controller where we check the posted data and, if the validation fails, we add the validation errors directly to the ModelState object. The ModelState is a property of the controller class that holds all the model-binding validation errors along with the raw values that were submitted to the server. Although this can seem to be the easiest method to apply validation it is the least recommended one because, according to the MVC pattern, the best place to implement data validation is at the model level since the model is responsible for defining the domain data and the business logic to apply on that data while the controller should implement only the application flow.
  2. Using DataAnnotation attributes – we can decorate the model properties using attributes that define common validation checks, for example we can mark a field as required or as having a given range of values. These attributes are defined in the System.ComponentModel.DataAnnotations namespace. When applied to a model property they will automatically check the value of the property and, in case of errors, will add them to the ModelState.
  3. Implementing the IDataErrorInfo interface in the model – this was the initial way of performing custom validation in MVC 1.0. Although it is still completely functional it is recommended that we use the IValidatableObject interface instead.
  4. Implementing the IValidatableObject interface in the model – IValidatableObject it’s a newer version of IDataErrorInfo used for server-side class-level validation and currently the recommended way of implementing complex server side validation that can target more than only one field.
  5. Client-side validation – some of the server side validation attributes provide also implicit client side validation. We will have a look on how to enable client-side validation.
  6. Remote Validation – allows us to make asynchronous calls to the server in order to validate the user input.

Next I will try to give an example for each validation method using the ‘Contact Us’ form that we created in the previous tutorial. This is what we did until now:

  1. We used Entity Framework (EF) to generate the data access classes for Messages and ContactReasons.The DB structure
  2. We created a new file under the Models folder where we added an additional partial class for the Message class that was generated by EF.
  3. In the same file we created an associated metadata class, called MessageMetaData, that we used to add attributes to some of the properties defined in the Message class. We need this additional class because, if we add attributes directly to the properties generated by EF, then, the next time the EF model will be modified/refreshed, the class would be recreated from scratch and our modifications would be lost.
  4. We linked the class MessageMetaData with our partial definition of the Message class using the MetadataTypeAttribute. In this moment our model definition looks like this:
    namespace HelloWorld.Code.DataAccess
    {
        [MetadataType(typeof(MessageMetaData))]
        public partial class Message
        {
           //Code omitted for brevity
        }
    
        public class MessageMetaData
        {
            [Display(Name = "E-mail")]
            public string Email { get; set; }
    
            [Display(Name = "Contact reason")]
            public int ContactReasonId { get; set; }
    
            [Display(Name = "Message")]
            public int Message1 { get; set; }
        }
    }
    

Now let’s add the following validation rules:
Contact Us Validation

  • the name is mandatory and it must be a string of at least 3 characters and at most 50 characters,
  • the e-mail is mandatory and must be a valid e-mail address with no more than 50 characters,
  • the user must select a contact reason,
  • the subject must be a string of at most 100 characters,
  • the message is required.

2. Adding validation errors directly to the ModelState

We will change the controller method that handles the HttpPost to include model validation and save the data only if the validation passed:

[HttpPost]
public ActionResult ContactUs(Code.DataAccess.Message message)
{
	//Name
	if(string.IsNullOrEmpty(message.Name))
		ModelState.AddModelError("Name", "Required");
	else if(message.Name.Length ❤ || message.Name.Length > 50)
		ModelState.AddModelError("Name", "The name must be a string of at least 3 characters and at most 50 characters");

	//Email
	if (string.IsNullOrEmpty(message.Email))
		ModelState.AddModelError("Email", "Required");
	else if (message.Email.Length > 50)
		ModelState.AddModelError("Email", "The e-mail can't have more than 50 characters");
	else if (!Regex.IsMatch(message.Email, @"^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$"))
		ModelState.AddModelError("Email", "Invalid e-mail");

	//ContactReasonId
	if(!message.ContactReasonId.HasValue)
		ModelState.AddModelError("ContactReasonId", "Required");

	//Subject
	if (string.IsNullOrEmpty(message.Subject))
		ModelState.AddModelError("Subject", "Required");
	else if (message.Subject.Length > 100)
		ModelState.AddModelError("Subject", "The subject must be a string with a maximum length of 100 characters");

	//Message
	if (string.IsNullOrEmpty(message.Message1))
		ModelState.AddModelError("Message1", "Required");

	if (ModelState.IsValid)
	{
		string saveResultMessage;
		ViewBag.SaveResult = message.Save(out saveResultMessage);
		ViewBag.SaveResultMessage = saveResultMessage;
	}
	return View(message);
}

Now, in order to display the validation errors, we will add into the view a validation element @Html.ValidationMessageFor(model => model.[[FieldName]]) for each of the fields in our model:

@model HelloWorld.Code.DataAccess.Message
@{
    ViewBag.Title = "Contact Us";
}
<h2>Contact Us</h2>
<hr />
@using (Html.BeginForm("ContactUs", "Home", FormMethod.Post))
{
    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)

    @Html.LabelFor(model => model.Email, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)

    @Html.LabelFor(model => model.ContactReasonId, new { @class = "control-label" })
    @Html.DropDownListFor(model => model.ContactReasonId, Model.ContactReasonsList)
    @Html.ValidationMessageFor(model => model.ContactReasonId)

    @Html.LabelFor(model => model.Subject, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Subject)
    @Html.ValidationMessageFor(model => model.Subject)

    @Html.LabelFor(model => model.Message1, new { @class = "control-label" })
    @Html.TextAreaFor(model => model.Message1)
    @Html.ValidationMessageFor(model => model.Message1)

    <input type="submit" name="Save" value="Save" />
}
@if (ViewBag.SaveResult != null && ViewBag.SaveResult)
{
    <span style="color: green;">@ViewBag.SaveResultMessage</span>
}
@if (ViewBag.SaveResult != null && !ViewBag.SaveResult)
{
    <span style="color: red;">@ViewBag.SaveResultMessage</span>
}

I also modified a little the CSS in “~/Shared/_Layout.cshtml” in order to color the error messages in red:

            body {
                 margin:0; 
                 padding:0;
            }
            #header_container {
                 background: black; 
                 color: white; 
                 height:60px; 
                 left:0; 
                 position:fixed; 
                 width:100%; 
                 top:0;
            }
            #header {
                 line-height:60px; 
                 margin:0 auto; 
                 padding-left: 50px; 
                 font-weight: bold;
                 font-size: 18pt;
            }
            #container {
                 margin:0 auto; 
                 overflow:auto; 
                 padding:80px 0; 
                 width:940px;
            }
            #container input[type=text], select, textarea  
            {
                width: 200px;
                margin: 2px;
                box-sizing: border-box;
                -moz-box-sizing: border-box;
                -webkit-box-sizing: border-box;
            }
            .control-label {
                width: 100px;
                display: inline-block;
                vertical-align: top;
            }
            .field-validation-error {
                color: red;
                vertical-align: top;
                padding-left: 5px;
            }
            .validation-summary-errors {
                color: red;
            }

If you run the site you will notice that the validation is applied. Anyway the code above is not nice, we repeated the required check a lot of times which contradicts with the DRY (Don’t Repeat Yourself) principle and, even worse, we placed model specific rules inside the controller. We will improve this in the next section by moving the validation inside the model and applying validation attributes.

3. Applying validation attributes

The System.ComponentModel.DataAnnotations namespaces contains a set of attributes that provide common validation capabilities. We will apply them in the MessageMetaData class in the same way we applied the [Display(“…”)] attribute for changing the UI text associated with a property.

public class MessageMetaData
{
	[Required(ErrorMessage = "Required")]
	[StringLength(50, MinimumLength = 3, ErrorMessage = "The name must be a string of at least 3 characters and at most 50 characters")]
	public string Name { get; set; }

	[Required(ErrorMessage = "Required")]
	[StringLength(50, ErrorMessage = "The e-mail can't have more than 50 characters")]
	[RegularExpression(@"^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$", ErrorMessage = "Invalid e-mail")]
	[Display(Name = "E-mail")]
	public string Email { get; set; }

	[Required(ErrorMessage = "Required")]
	[Display(Name = "Contact reason")]
	public int? ContactReasonId { get; set; }

	[Required(ErrorMessage = "Required")]
	[StringLength(100, ErrorMessage = "The subject must be a string with a maximum length of 100 characters")]
	public string Subject { get; set; }

	[Required(ErrorMessage = "Required")]
	[Display(Name = "Message")]
	public string Message1 { get; set; }
}

And, of course, we will remove the previous code we added in the controller for managing validation:

[HttpPost]
public ActionResult ContactUs(Code.DataAccess.Message message)
{
	if (ModelState.IsValid)
	{
		string saveResultMessage;
		ViewBag.SaveResult = message.Save(out saveResultMessage);
		ViewBag.SaveResultMessage = saveResultMessage;
	}
	return View(message);
}

4. Implementing model validation with IDataErrorInfo

When Entity Framework generates an entity class, it automatically creates two partial methods for each property of the class:

  1. OnChanging method, that is called right before the corresponding property is changed and
  2. OnChanged method, that is called right after the property is changed.

So, for the models that are based on Entity Framework, we can add validation for each individual field by implementing the partial method that handles the changes for that data field. For example, we will add validation for the Name field making sure that the user entered at least two words (name and surname). We will provide an implementation for the partial method OnNameChanging inside the partial class definition that we created inside the Models folder.

[MetadataType(typeof(MessageMetaData))]
public partial class Message
{
	#region Validation

	partial void OnNameChanging(string value)
	{
		if(string.IsNullOrEmpty(value) || value.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries).Length < 2)
			throw new ValidationException("Please enter your name and surname");
	}

	#endregion

	//code removed for brevity
}

At this point, if we run the site, we will notice that the validation is applied but the error message is different than the one we’ve set in the ValidationException:
Using ValidationExceptionIn order to pass the validation messages from the model to the user interface we will implement in the model the IDataErrorInfo interface.

[MetadataType(typeof(MessageMetaData))]
public partial class Message : IDataErrorInfo
{
	#region Validation

	partial void OnNameChanging(string value)
	{
		if(string.IsNullOrEmpty(value) || value.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries).Length < 2)
			_errors.Add("Name", "Please enter your name and surname");
	}

	#region IDataErrorInfo Members

	public string Error { get; private set; }

	private readonly Dictionary<string, string> _errors = new Dictionary<string, string>();
	public string this[string columnName]
	{
		get
		{
			return _errors.ContainsKey(columnName) ? _errors[columnName] : string.Empty;
		}
	}

	#endregion

	#endregion

	//Code omitted for brevity
}

Now we are able to see the correct error message because, when the posted form is bound to the model, the model binder checks to see if the model class implements the IDataErrorInfo interface. If it does, then it will invoke the IDataErrorInfo.this indexer for each property of the class in order to check for errors and add them to the ModelState dictionary. The model binder will also check the value of the property IDataErrorInfo.Error. This property can be used to set validation errors that are not specific to any property. We can use it to enforce complex validation rules that target multiple fields in the model.

Although IDataErrorInfo is completely supported in MVC 4 it is recommended that we use IValidatableObject which is a newer interface that was introduced starting with .NET framework 4.0.

5. Implementing model validation with IValidatableObject

This interface contains only one method IEnumerable Validate(ValidationContext validationContext) that is supposed to contain all the validation rules that a model needs to pass. Note that the model binder will call the Validate method only if there are no errors in the model’s properties.
We will extend our model class to include 2 new validation rules:
– The subject and the message can’t contain the same text,
– We can’t add a new message if we already have in the DB another message with the same subject and from the same user.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
	//Thow an error if the subjct and the message are the same
	if (string.Compare(Subject.Trim(), Message1.Trim(), true) == 0)
	{
		yield return new ValidationResult("The subject and the message can't be the same.");
	}

	//Throw an error there is another message with the same subject from the same person
	using (var context = new MvcDemoEntities())
	{
		var existingMessage = context.Messages.FirstOrDefault(m => string.Compare(m.Name.Trim(), Name.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0 &&
																   string.Compare(m.Subject.Trim(), Subject.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);
		if(existingMessage != null)
		{
			yield return new ValidationResult("A message with the same subject was previously saved in the DB.", new []{"Subject"});
		}
	}
}

The IValidatableObject.Validate() method can apply validation rules that target multiple properties, and can yield back multiple validation errors. Each ValidationResult object contains an optional list of property names that caused the rule violation, which will be used when displaying the error messages in the UI. In our example you can see that the validation error message “The subject and the message can’t be the same.” is not related to any specific model property while the other error message (“A message with the same subject was previously saved in the DB.”) is associated to the Subject field. The errors that are associated to properties will be displayed in the view by @Html.ValidationMessageFor(model => model.[[FieldName]]). In order to display also the general errors that are related to the model state in general and not to a specific field we can use @Html.ValidationSummary(true). The true parameter inside the helper method indicates that we want to display in the validation summary only the error messages that are unrelated to properties. Now our view looks like this:

@model HelloWorld.Code.DataAccess.Message
@{
    ViewBag.Title = "Contact Us";
}
<h2>Contact Us</h2>
<hr/>
@Html.ValidationSummary(true)
@using (Html.BeginForm("ContactUs", "Home", FormMethod.Post))
{
    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
    <br/>
    @Html.LabelFor(model => model.Email, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)
    <br/>
    @Html.LabelFor(model => model.ContactReasonId, new { @class = "control-label" })
    @Html.DropDownListFor(model => model.ContactReasonId, Model.ContactReasonsList)
    @Html.ValidationMessageFor(model => model.ContactReasonId)
    <br/>
    @Html.LabelFor(model => model.Subject, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Subject)
    @Html.ValidationMessageFor(model => model.Subject)
    <br/>
    @Html.LabelFor(model => model.Message1, new { @class = "control-label" })
    @Html.TextAreaFor(model => model.Message1)
    @Html.ValidationMessageFor(model => model.Message1)
    <br/>          
    <input type="submit" name="Save" value="Save" />  
}
@if (ViewBag.SaveResult != null && ViewBag.SaveResult)
{
    <span style="color: green;">@ViewBag.SaveResultMessage</span>
}
@if (ViewBag.SaveResult != null && !ViewBag.SaveResult)
{
    <span style="color: red;">@ViewBag.SaveResultMessage</span>
}

And if we run the the site we can see the validation we added with IValidatableObject.
IValidatableObject result

6. Implementing client side validation

The MVC framework comes with some built-in client-validation support. Basically, the DataAnnotation attributes are able to support also client-side validation and, in this section, I will show the steps you need to do in order to enable it.

  • First make sure that the client-side validation is enabled in the web.config that is, the following two properties are set to true:
    <appSettings>
         <add key="ClientValidationEnabled" value="true"/>
         <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    </appSettings>
    

    Notes:
    – This enables client-side validation for the entire site, if you want to enable it only for specific views, you can do this using code blocks inside the view and calling HtmlHelper.ClientValidationEnabled(true) and HtmlHelper.UnobtrusiveJavaScriptEnabled(true).
    – The MVC Framework supports unobtrusive client-side validation, meaning that the validation rules are defined using HTML data attributes instead of emitting client side JavaScript. Then, these attributes are processed with JavaScript in order to add the validation rules. The current MVC framework validation is based on the jQuery Validation library.

  • Then we have to add in our project the JavaScript files needed for validation. The easiest way is to use NuGet. Right click on References in Solution Explored and click on ‘Manage NuGet Packages…’. In the window that opens make sure that the Online section is selected and search for jQuery. Fron here you can install: jQuery, jQuery Validation and Microsoft jQuery Unobstructive Validation.
    Adding validation libraries using NuGet
  • Now we will include those files in the _Layout.cshtml file, just before the “scripts” section, so they will be available in all our pages.
    <script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    @RenderSection("scripts", required: false)
    

    Note: It would be better to include those files using Bundling, which is a new feature in asp.net MVC 4 that allows us to easily combine/bundle multiple JavaScript/CSS files into a single file so that we reduce the number of file requests which will improve the first page load performance. But, for keeping things simple we don’t use bundling for the moment.

  • If you run now the application you will notice that the validation we added with DataAnnotation attributes takes place on the client-side with no post back to the server.

7. Implementing remote validation

Sometimes we need to make some checks that require some server-side resources and can not be implemented only with client-side code. For example, in the context of user accounts, when registering a new account we might want to check if a username is not already taken. We can implement this with as a server-side validation but this will generate a round-trip to the server and it would be nicer to make the check via Ajax. The MVC framework provides support for remote validation with the help of the [Remote] attribute. Let’s use it to check if there is another message in the DB from the same e-mail address. We will add a remote attribute to the Email property:

[Remote("ValidateEmail", "Home")]

The first parameter specifies the method used for validation and the second parameter indicates the name of the controller that contains the validation method. So in our Home controller we will add:

public JsonResult ValidateEmail(string email)
{
	string message;
	return Message.EmailAlradyExists(email, out message)
			   ? Json(message, JsonRequestBehavior.AllowGet)
			   : Json(true, JsonRequestBehavior.AllowGet);
}

And now we add inside the model the method that actually connects to the DB to check if the e-mail was already used. Please remember that we shouldn’t place data access calls or business rule validation inside the controller.

public static bool EmailAlradyExists(string email, out string validationMessage)
{
	validationMessage = string.Empty;
	using (var context = new MvcDemoEntities())
	{
		var result = context.Messages.Any(m => string.Compare(m.Email, email, StringComparison.CurrentCultureIgnoreCase) == 0);
		if (result)
			validationMessage = "This e-mail address is already used";

		return result;
	}
}

So, when we use the [Remote(“ActionMethodName”,”ControllerName”)] attribute the MVC framework uses jQuery to make an asynchronous call to the server in order to check the validation rule defined in the action method. This explains why we are returning a JsonResult from the ActionMethodName. Now, if you run the site and enter an already used e-mail, when the e-mail text box looses the focus, the remote validation will be fired and you will see an error message like in the image below.
Remote validation

8. Summary

In this post we implemented data validation at the model level and we displayed the error messages in the user interface making use of the helper methods Html.ValidationMessageFor and Html.ValidationSummary.

We showed that even if it is possible to add validation rules in the controller it is not recommended to do so because the controller should contain only logic related to the application flow control hence we should always implement data validation in the model because it’s its role to define the domain data and the business logic to apply on that data.

We showed how DataAnnotation attributes can provide an easy way to validate individual properties on the model and, for more complex validation validation rules, we implemented the IValidatableObject interface.

Finally you can download the source code of this second MVC demo application from Codeplex.

Introduction to MVC

Contents:

  1. Basic concepts
  2. Advantages of MVC
  3. From HTTP to Routes
  4. A Hello World application
  5. Adding a master page
  6. How to create a ‘Contact us’ form

1. Basic concepts

The Microsoft ASP.NET Model-View-Controller (MVC) is a web development framework that comes as an alternative to the standard ASP.NET Web Forms model. This alternative is based on a common software architecture design pattern called MVC.

A design pattern is a general reusable solution to a commonly occurring problem and can be seen as a best practice in the field.

The main purpose of MVC is to separate an application into 3 distinct parts so that the complexity of each part is decreased. This idea is very similar to the divite et impera concept. In addition to this separation MVC defines also the interactions between these 3 components:

  • Model – contains the data and the business logic,
  • View – defines the user interface and displays the model data,
  • Controller – connects the view and the model and controls the input handling.

mvc In simple words, the application flow can be summarized like this: when an event occurs (e.g. a user requests a page), the controller is invoked and is its responsibility to understanding what kind of event occurred, what action to do (e.g. update some data in a model) and what view to render as a response to that event. Except for the very simple cases, the view needs to receive a model as an input in order to know what content to render. If this is the case, the controller is also responsible for instantiating the correct model and passing it to the view.

This separation into components is called in the literature separation of concerns and it helps to minimize the impact a modification in one component has on the other components. For example, if we need to change the way the data is displayed, it should be enough to change the view without having to modify the business logic inside the model.

2. Advantages of MVC

The main advantage that comes from using the MVC pattern is that the application is divided into components avoiding the mixing of the code into a single big monolithic application. Apart from this we have another set of advantages that come rather from the way the new Microsoft MVC framework is written than from the pure concept of MVC. After all MVC is only an architectural pattern, a way of structuring an application. Nothing more and nothing less!

As everybody already knows, with the Web Forms, Microsoft tried to wrap the HTML controls into .net objects that are able to automatically remember between post backs the values of their properties by making use of the view state. This has 2 negative impacts:

  1. the view state is ugly and unacceptably big for medium to large pages and
  2. the HTML that the .net controls render is usually hard to control and change. For example the id of the elements is unnecessarily long. This was fixed with the introduction of the static client id mode but still the name attribute of the controls keeps the old format.

With the MVC framework the view state is removed and we have complete control on the rendered HTML.

Another advantage that comes from the way in which the MVC web development framework is implemented and not from the MVC pattern itself is that the complicated Page Life Cycle set of events was removed and we now have a simplified execution pipeline. The main purpose of the Page Life Cycle was to hide the way in which the communication between the client and the server happens and automatically bind user interface events, like the click of a button, with server side methods that would handle that event, creating the impression that the web interaction is event-driven and similar to the way Windows applications work. Though this was a nice idea in the beginning, time proved that it adds a lot of complexity:

  • understanding the Page Life Cycle is not a trivial job, and
  • it tends to make the pages monolithic, for example, in order to execute a button’s click event handler first the page initialization and loading events are executed, making all those event methods tightly coupled.

So, with no .net wrapper controls, no view state and no page life cycle the MVC framework doesn’t try to hide the way HTTP anf HTML work and offers a more elegant and simple development framework. Now, since we no longer have the abstractions provided by the Web Forms it’s better to get started by making sure all the basic concepts about how the web actually works are clear.

3. From HTTP to Routes

The Hypertext Transfer Protocol (HTTP) is an application level response-request protocol that defines the set of rules used by 2 participants (a client and a server) in order to communicate. Or, a more memorable definition taken from this nice book RESTful Web Services: “HTTP is the one thing that all ‘animals’ on the programmable web have in common.”

When a page is requested, the browser sends a request to the web server. The first 2 lines of a request look like this:Fiddler
Note: For inspecting the request text I used Fiddler which it’s a very useful tool that can help you see all the HTTP(S) traffic between your computer and the Internet.

The first word in the request is the HTTP method (in the example: GET). It is followed by the Uniform Resource Identifier (URI) of the resource to be retrieved (http://wordpress.com/) and the HTTP version to be used for processing the command (HTTP/1.1). The second line (Host: wordpress.com) identifies the name of the website and is used by the servers that host multiple websites under a single IP address to understand what is the website the page belongs to.

So, a request message from a client to a server includes (within the first line of that message) the method to be applied to the resource, the identifier of the resource, and the protocol version to use.

The HTTP methods, also known as HTTP verbs, are tokens that indicate the action to be performed on a resource and are very important for us because we will use them together with the URIs to map an incoming browser request to a particular MVC controller action.

Below is a list of possible methods, as defined by the World Wide Web Consortium (W3C):

  1. OPTIONS – represents a request for information about the communication options available on the request/response chain identified by the request URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. Responses to this method are not cacheable. Simply said, you can use OPTIONS to check if a server allows a particular command and avoid wasting network bandwidth trying to send an unsupported request.
  2. GET – means: retrieve whatever information is identified by the request URI.
  3. HEAD – is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method can be used for testing hypertext links for validity, accessibility, and recent modification. HEAD is typically used to verify that a resource didn’t change since the browser cached it.
  4. POST – requests that the origin server accepts the entity enclosed in the request as a new subordinate of the resource identified by the request URI. The actual function performed by the POST method is determined by the server and is usually dependent on the request URI. POST is designed to allow a uniform method to cover the following functions:
    • Annotation of existing resources;
    • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
    • Providing a block of data, such as the result of submitting a form, to a data-handling process;
    • Extending a database through an append operation.
  5. PUT – requests that the enclosed entity be stored under the supplied request URI. If the request URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the request URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. So, simply said, PUT allows a client to add a resource to the server at the specified URI. If the user has permissions, the server creates the file specified in the URI and copies the request body to the newly created file.
  6. DELETE – requests that the origin server deletes the resource identified by the request URI.
  7. TRACE – is used for testing or diagnostics information and allows a client to see what is being received at the other end of the request chain.
  8. CONNECT – is reserved to be used with a proxy that can dynamically switch to being a tunnel (e.g. SSL tunneling).

Notes:
– The HTTP methods are case-sensitive.
– As specified by the W3C the methods GET and HEAD MUST be supported by all general-purpose servers. All other methods are OPTIONAL; however, if they are implemented, they MUST be implemented with the semantics previously explained.

Now, after so much talking is time to move on and do something practical, and that obviously is a Hello World application.

4. A Hello World application

Let’s start with the classic ‘File’ -> ‘New’ -> ‘Project’ but this time we will create an ‘ASP.NET MVC 4 Web Application’ :D.
Create a new MVC project
The next step is to select a project template. Please choose the empty project template and then make sure that the selected view engine is Razor.
Select the project templateA view engine is a pluggable module that provides a way to insert dynamic blocks into a template and is able to render that template to HTML or whatever content type it is designed to emit. There are 2 available view engines:

  1. one is the old ASPX that uses code blocks separated by <% tags %>,
  2. the other one is Razor that uses the character @ in order to indicate the beginning of a code block and doesn’t require the explicit closing of the code block.

Razor is not a new language, and it’s actually very easy and intuitive, it helps to create a template that contains static HTML and C# code blocks that can render dynamic content. So, we will use Razor for creating the Views.

Looking at the structure of our new empty project we see that we have a dedicated folder for the controllers, one for the models and one for the views plus another folder called App_Start that contains a RouteConfig.cs file. This file is used to define the allowed URLs and the association between an URL and the controller that will process that request.
Defining the routesEach route must:

  • have an unique name, otherwise we will receive an error
  • and must define the structure of the allowed URLs. In the example, the URLs are composed by 3 parts: the controller name {controller}, the name of the method inside the controller that will handle the request {action} and an identifier {id}.

The last line defines the default values to be used in case a part of the URL is missing. For example, if the root of the web site is requested (http://site-name/) the default controller that will be called is ‘Home’ and the default action is ‘Index’. The last parameter is optional so it will be empty.

Now, let’s add a controller called ‘Home’ in order to see how the routing works. In Solution Explorer right click on the Controller folder -> Add -> Controller. Name the new controller ‘HomeController’. Note that the naming convention for controllers is: Name + Controller and using another name, for example only ‘Home’ will make the controller unreachable.
Add a new controllerLet’s replace the default implementation of the index method with the following:

        public string Index()
        {
            return "Hello world!";
        }

Now, if we run the site, we will see the text ‘Hello world!’. If we want to use also the {id} part of the URL we can change the Index action like this:

        public string Index(string id)
        {
            return string.IsNullOrEmpty(id) ? "Hello world!" : string.Format("Hello world! Your id is: {0}.", id);
        }

So calling http://site-name/home/index/Hey we will see the text: ‘Hello world! Your id is: Hey.’. Note that here we have another naming convention, that is, the name of the input parameter matches the 3rd part of our route {id}, if the name of the parameter would have been different the displayed text would be ‘Hello world!’.

Next thing to do is to add a view file for returning HTML content rather than a string. A fast way of doing this is to right click on the action name and select ‘Add View’:
Add a new view
Let’s replace the default content of the view with the following one:

@{
    ViewBag.Title = "Home";
}
<h2>Hello from the view.</h2>
@if(!string.IsNullOrEmpty(ViewBag.Id))
{
    <text>Your id is: @ViewBag.Id.</text>
}

<i>@ViewBag.Message</i>

and update the Index action method like this:

        public ActionResult Index(string id)
        {
            ViewData["Message"] = "This is a string created in the controller";
            ViewBag.Id = id;
            return View();
        }

The first thing to notice here is the ViewData which is a dictionary that we can use to pass data from the controller to the view. The ViewBag is a dynamic type created as a wrapper over the ViewData that allows us to use dynamic properties instead of strings for accessing the objects in the ViewData. As you can see in the last line of the view, we can access the value in ViewData[“Message”] by calling @ViewBag.Message.

The last line in the action method tells the rendering engine to return the view associated with this action. To find the correct view, another naming convention is applied. The implicit view should be located under the Views folder in a sub-folder with the same name as the controller (‘Home’) and the name of the file should match the name of the action method (‘Index.cshtml’). Note that it is possible to render a different view, for this we have to pass the name of the view as a parameter to the View method.

5. Adding a master page

Our next goal is to define a common layout for the entire site. To do this we have to add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) under the Views folder of the project.

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

_ViewStart.cshtml indicates what file to use as a master page. It is recommended that we store the common layout files under the folder ‘~/Views/Shared’ and that we prefix the name of those files with an underscore, like _Layout.cshtml so, let’s stick to the recommendations and add the folder Shared and the file _Layout.cshtml with the following content:

<!DOCTYPE html>
<html>
    <head>
       <title>MVC - @ViewBag.Title</title>
        <style type="text/css">            
            body { margin:0; padding:0; }
            #header_container { background: black; color: white; height:60px; left:0; position:fixed; width:100%; top:0; }
            #header { line-height:60px; margin:0 auto; padding-left: 50px; font-weight: bold;font-size: 18pt;}
            #container { margin:0 auto; overflow:auto; padding:80px 0; width:940px; }
            .control-label{ width: 120px;display: inline-block;}
        </style>
    </head>
    <body>       
        <div id="header_container">
            <div id="header">
                <i>=(^.^)=</i>
            </div>
        </div>              
        <div id="container">
            <div id="content">
                @RenderBody()    
            </div>
        </div>
        @RenderSection("scripts", required: false)
    </body>
</html>

The code it’s pretty straight forward:
– @RenderBody() will render the content of a view that is not within any named sections,
– @RenderSection(“scripts”, required: false) – if the view contains a section called scripts it renders the content of that section.

To define the scripts section inside Index.cshtml just add at the end of the file the following:

@section scripts{
<script type="text/javascript">
    document.getElementById("header").innerHTML += ' MVC'
</script>
}

Now, that we have such a nice layout plus some text inserted via JavaScript, let’s add a ‘Contact us’ page that will allow our visitors to praise our great design. We will save all the positive comments in the DB so we can show to the managers how great we are!

6. How to create a ‘Contact us’ form

Contact Us Form
First thing first, let’s create a DB and use Entity Framework to access it. Our DB will have these 2 tables:
The DB structure I named the new DB [MvcDemo]. Below is the script for creating the tables:

USE [MvcDemo]
GO
/****** Object:  Table [dbo].[ContactReasons]    Script Date: 03/12/2013 21:51:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ContactReasons](
	[ContactReasonId] [int] IDENTITY(1,1) NOT NULL,
	[ContactReasonText] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_ContactReasons] PRIMARY KEY CLUSTERED 
(
	[ContactReasonId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Messages]    Script Date: 03/12/2013 21:51:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Messages](
	[MessageId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Email] [nvarchar](50) NOT NULL,
	[ContactReasonId] [int] NULL,
	[Subject] [nvarchar](100) NOT NULL,
	[Message] [text] NOT NULL,
 CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED 
(
	[MessageId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  ForeignKey [FK_Messages_ContactReasons]    Script Date: 03/12/2013 21:51:40 ******/
ALTER TABLE [dbo].[Messages]  WITH CHECK ADD  CONSTRAINT [FK_Messages_ContactReasons] FOREIGN KEY([ContactReasonId])
REFERENCES [dbo].[ContactReasons] ([ContactReasonId])
GO
ALTER TABLE [dbo].[Messages] CHECK CONSTRAINT [FK_Messages_ContactReasons]
GO

USE [MvcDemo];
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO
SET IDENTITY_INSERT [dbo].[ContactReasons] ON;
BEGIN TRANSACTION;
INSERT INTO [dbo].[ContactReasons]([ContactReasonId], [ContactReasonText])
SELECT 1, N'Positive remark' UNION ALL
SELECT 2, N'Negative remark'
COMMIT;
RAISERROR (N'[dbo].[ContactReasons]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;
GO
SET IDENTITY_INSERT [dbo].[ContactReasons] OFF;
GO

We will use Entity Framework to connect to the DB, so let’s create a new EF file ‘MvcDemoDb.edmx’ under the folder ‘~/Code/DataAccess’. This is how the solution looks now:
Project structure after adding EFNow, let’s add a new action method in the Home controller called ContactUs and a new view for this action. This time, when creating the view, tick the ‘Create a strongly-typed view’ check-box and enter as the model class: HelloWorld.Code.DataAccess.Message.
Create a contact us viewLet’s add inside the view the code below:

@model HelloWorld.Code.DataAccess.Message

@{
    ViewBag.Title = "Contact Us";
}

<h2>Contact Us</h2>
<hr/>
@using (Html.BeginForm("ContactUs", "Home", FormMethod.Post))
{
    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Name)
    <br/>
    @Html.LabelFor(model => model.Email, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Email)
    <br/>
    @Html.LabelFor(model => model.ContactReasonId, new { @class = "control-label" })
    @Html.DropDownListFor(model => model.ContactReasonId, new List<SelectListItem>())
    <br/>
    @Html.LabelFor(model => model.Subject, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Subject)
    <br/>
    @Html.LabelFor(model => model.Message1, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Message1)
    <br/>
    <input type="submit" name="Save" value="Save" />
}

In the above code, the syntax Html.BeginForm is used to create a HTML form element. Here Html is a property of the view and it’s an instance of the HtmlHelper class. The HtmlHelper class provides methods that can be used to generate HTML elements programatically. All the methods of the HtmlHelper class generate HTML and return the result as a string. There are a lot of extension methods for the HtmlHelper class and, in the next posts, I will show how we can create our own custom extensions. So @Html.LabelFor(model => model.Name, new { @class = “control-label” }) will create a label element for the property Name of the model. With new { @class = “control-label” } we create a dictionary object that contains the HTML attributes to set to the element. In our example the rendered HTML will be:

 
<label class="control-label" for="Name">Name</label>

Try to enter some data and press the save button. You will notice that the values entered are not remembered after the post back. This is the expected behavior since we are not using the view state any more. Let’s have a look at the request with Fiddler and see what’s sent to the server.
Inspect the post data with FiddlerSo we have a POST to /Home/ContactUs that results in the action method ContactUs being called. In MVC we have a set of attributes that we can use to restrict what HTTP verbs an action method will handle. We can use [HttpGet] and [HttpPost] to indicate that an action method will be called only for GET/POST requests. Knowing this, we can modify our controller class and add a new custom action that will handle only the POST method, which, in our case, means that the user pressed the save button:

[HttpGet]
public ActionResult ContactUs()
{
	return View(new Code.DataAccess.Message());
}

[HttpPost]
public ActionResult ContactUs(Code.DataAccess.Message message)
{
	return View(message);
}

The new ContactUs method receives a message object that is filled automatically with the data the user inserted. This happens because we used in the view the HtmlHelper method @Html.TextBoxFor that created form elements with the same name as the model properties and now the MVC framework can automatically map the HTML form elements with the model properties based on the name. When rendering the response we will pass this message object back to the View and now we can notice that the data the user entered remains filled also after a post back.

The next thing that we can improve is the text that appears in the labels. For example we want to display ‘Contact reason’ instead of ‘ContactReasonId’. There is a little trick for doing this and it is called the MetadataTypeAttribute. We are going to add in our Models folder a new file and we will extent here the class HelloWorld.Code.DataAccess.Message. We can do this because the Message class is partial which means that we can split the definition of the class in more files. Please make sure that the class name and the namespace name are identical to the one generated by the entity framework model, otherwise you will be creating a new class instead of adding new elements to the existing partial class.

using System.ComponentModel.DataAnnotations;

namespace HelloWorld.Code.DataAccess
{
    [MetadataType(typeof(MessageMetaData))]
    public partial class Message
    {
    }

    public class MessageMetaData
    {
        [Display(Name = "E-mail")]
        public string Email { get; set; }

        [Display(Name = "Contact reason")]
        public int ContactReasonId { get; set; }

        [Display(Name = "Message")]
        public int Message1 { get; set; }
    }
}

The MessageMetaData defines additional attributes for our Message class. This type of helper class is called a buddy class. The display attribute sets the UI text to associate to a property and needs to be declared in a buddy class because, in this way, we don’t have to change the file generated by the EF that will be overridden the next time we will change the EF edmx file. Note that the properties defined in the MessageMetaData class are exactly the same as the ones defined in the Message class that was generated by the entity framework, otherwise the mapping would fail. If we see now the contact us page we can notice that the label text is changed. Next, we will populate the contact reason drop-down. First we define the collection in the model:

public IEnumerable<SelectListItem> ContactReasonsList
{
	get
	{
		using (var context = new MvcDemoEntities())
		{
			return (new[]
					{
						new SelectListItem
							{
								Selected = (ContactReasonId == 0),
								Text = "Select...",
								Value = string.Empty
							}
					}).Union(context.ContactReasons.
									 Select(c => new SelectListItem
									 {
										 Selected = (c.ContactReasonId == ContactReasonId),
										 Text = c.ContactReasonText,
										 Value = c.ContactReasonId.ToString(CultureInfo.InvariantCulture)
									 }));
		}                
	}
}

and then we use it in the view:

@Html.DropDownListFor(model => model.ContactReasonId, Model.ContactReasonsList)

The code above speaks for itself BUT it has a big problem: each time the view is rendered a call to the DB is made to retrieve the contact reasons. So we need to implement a basic caching mechanism. I’ll just put the code here, if you need more details check this post where you can find some explanations.

public static class CacheManager
{
	/// <summary>
	/// Get the list of contact reasons
	/// </summary>
	/// <param name="getFromCache"></param>
	/// <returns></returns>
	public static List<ContactReason> GetContactReasons(bool getFromCache)
	{
		return (List<ContactReason>)GetFromCache("ContactReasons", getFromCache, delegate
		{
			using (var context = new MvcDemoEntities())
			{
				return context.ContactReasons.OrderBy(c => c.ContactReasonText).ToList();
			}
		});
	}

	#region Private methods

	/// <summary>
	/// Helper method for adding/retrieving a value from/to the cache.
	/// </summary>
	/// <param name="cacheKey">The key of the cached item</param>
	/// <param name="f">If the key is not found in the cache execute the f() function to retrieve the object</param>
	/// <returns></returns>
	private static object GetFromCache(string cacheKey, Func<object> f)
	{
		return GetFromCache(cacheKey, true, f);
	}

	/// <summary>
	/// Helper method for adding/retrieving a value from/to the cache.
	/// </summary>
	/// <param name="cacheKey">The key of the cached item</param>
	/// <param name="getFromCache">True if a cached vaersion cand be returned. If false, f() will be used to get the data</param>
	/// <param name="f">If the key is not found in the cache execute the f() function to retrieve the object</param>
	/// <returns></returns>
	private static object GetFromCache(string cacheKey, bool getFromCache, Func<object> f)
	{
		object cachedItem = null;
		if (getFromCache)
			cachedItem = HttpRuntime.Cache[cacheKey];

		if (cachedItem == null)
		{
			cachedItem = f();
			if (cachedItem != null)
				HttpRuntime.Cache.Insert(cacheKey, cachedItem, null, DateTime.Now.AddSeconds(WebConfigSettings.CachingTime), TimeSpan.Zero);
		}

		return cachedItem;
	}

	#endregion
}

Below the modification to be done in the model:

public IEnumerable<SelectListItem> ContactReasonsList
{
	get
	{
		return (new[]
					{
						new SelectListItem
							{
								Selected = (ContactReasonId == 0),
								Text = "Select...",
								Value = string.Empty
							}
					}).Union(CacheManager.GetContactReasons(HttpContext.Current.Request.HttpMethod == "POST").
								 Select(c => new SelectListItem
								 {
									 Selected = (c.ContactReasonId == ContactReasonId),
									 Text = c.ContactReasonText,
									 Value = c.ContactReasonId.ToString(CultureInfo.InvariantCulture)
								 }));              
	}
}

And now the final touch, implementing the save with our preferred business logic (save in the DB only the positive comments). Of course, the business logic goes in the model:

public bool Save(out string message)
{
	try
	{
		using (var context = new MvcDemoEntities())
		{
			if (ContactReasonId == 1) //A positive remark
			{
				context.Messages.AddObject(this);
				message = "Your message was saved successfully. Thank you for your appreciation!";
				context.SaveChanges();
				return true;
			}                   
			message = "We are sorry you were disappointed.";
			return false;                                        
		}
	}
	catch (Exception exp)
	{
		message = "An unexpected error occured.";
		return false;
	}
}

then we call the save method from the controller

[HttpPost]
public ActionResult ContactUs(Code.DataAccess.Message message)
{
	string saveResultMessage;
	ViewBag.SaveResult = message.Save(out saveResultMessage);
	ViewBag.SaveResultMessage = saveResultMessage;
	return View(message);
}

and display the result in the view.

@if (ViewBag.SaveResult != null &amp;&amp; ViewBag.SaveResult)
{
    <span style="color:green;">@ViewBag.SaveResultMessage</span>
}
@if (ViewBag.SaveResult != null &amp;&amp; !ViewBag.SaveResult)
{
    <span style="color:red;">@ViewBag.SaveResultMessage</span>
}

This is it, now we have a completely functional ‘Contact Us’ and we can add a link to it in our default page:

@Html.ActionLink("Contact Us", "ContactUs", "Home")

Download the source code from CodePlex

Ajax like file upload

It is not possible to upload a file to the server through Ajax because the access to the local file system using JavaScript is forbidden but we can use a hidden IFrame in order to obtain an Ajax like behavior. This can be done in the following way:

  1. Create a form element that contains a file upload, an IFrame and a button.
  2. Set the name attribute of the child IFrame to a value (ex: uploadIframe)
  3. Set the target attribute of the containing form element to the name of the child iFrame (uploadIframe). The target attribute specifies where to open the action URL.
  4. In order to know the result of the upload, the IFrame will contain some JavaScript code that will set the result of the operation.

Below is a code example in asp.net MVC:

  • The main form:
    <form action='@Url.Action("UploadFile", "Home")' id="formContainer" method="post"  target="uploadIframe" enctype="multipart/form-data">
        <input type="file" name="fileUpload" id="fileUpload" />              
    </form>
    <input type="submit" value="Upload File" id="buttonUploadFile" name="buttonUploadFile"/>
    <p id="result"></p>
    
    @section scripts {
    <script type="text/javascript">
        $().ready(function () {
            $('#buttonUploadFile').click(function (event) {
                event.preventDefault();
                $('#result').text('Upload started');
                $('#formContainer').submit(); //submit the file to the server
            });
        });
    </script>
    }
    
  • The controller method that will upload the file:
    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase fileUpload)
    {
    	try
    	{
    		if (fileUpload != null && fileUpload.ContentLength > 0)
    		{
    			var fileName = Path.GetFileName(fileUpload.FileName);
    			var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
    			fileUpload.SaveAs(path);
    			ViewBag.FileUploadResult = "Success";
    		}
    		else
    			ViewBag.FileUploadResult = "No file to upload";
    	}
    	catch (Exception ex)
    	{
    		ViewBag.FileUploadResult = string.Format("Error: {0}", ex.Message);
    	}
    
    	return View();
    }
    
  • The content of the IFrame page (contains only a script that sets the result of the upload):
    @section scripts {
        <script type="text/javascript">
            $().ready(function () {
                //set the result in the parent page
                window.parent.$('#result').text('@ViewBag.FileUploadResult');
        });
    </script>
    }
    

Download the source code from CodePlex