Website Design Chester by the Informatics Centre

Model-View-Controller

Model-View-Controller (MVC) is a design pattern with a focus on the separation of concerns between the presentation of an application and its interaction with users. ASP.NET MVC is an implementation of the MVC design pattern which provides an alternative approach to that of traditional ASP.NET Web Forms in designing web applications. This post will discuss the differences between the two approaches.

The Model

The Model consists of the application data and the business logic for storing and retrieving the data, such as validation and formatting logic. In ASP.NET MVC, the Model for each entity will be stored in a C# class file. Each property of the entity can be annotated with validation and formatting rules, such as the data type required, whether it is a required field and the name which should be displayed to the user when referring to the property. An example of Model code is shown below.


using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;



namespace CO6025.Models

{

    public class Post

    {

        [Key]

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

        public int Id { get; set; }

        [Required]

        public string Title { get; set; }

        [Required]

        [DataType(DataType.MultilineText)]

        public string Content { get; set; }

        [Display(Name = "Date")]

        [DataType(DataType.DateTime)]

        public DateTime PostDateTime { get; set; }

        [Display(Name = "Last Updated")]

        [DataType(DataType.DateTime)]

        public DateTime LastUpdated { get; set; }

        public virtual UserDetail Author { get; set; }

        public virtual ICollection Categories { get; set; }

    }

}

The line �[Display(Name = �Date�)]�, for example, means that the PostDateTime property will simply be referred to as Date when it is displayed to the user. In ASP.NET Web Forms, this logic would need to be placed in the code-behind .aspx.cs file for each web form, or in a separate C# class file, if the functionality is shared by multiple pages. This makes it easier to comply with the Don't Repeat Yourself (DRY) principles in ASP.NET MVC, as the business logic for each entity can be stored in one place.

The View

The View presents information from the application to the user. It is equivalent to the .aspx HTML files in ASP.NET Web Forms. The View, however, can have an associated Model. These strongly-typed Views allow the properties of the associated Model object to be retrieved and displayed to the user. An example of some View code is shown below.


@model CO6025.Models.Post



@{

    ViewBag.Title = "Edit Post";

}



@ViewBag.Title

@if (User.IsInRole("Administrator") || (User.IsInRole("Contributor") && Model.Author.UserName == User.Identity.Name)) {

@ViewBag.StatusMessage

using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)
Post @Html.HiddenFor(model => model.Id) @Html.HiddenFor(model => model.PostDateTime) @Html.HiddenFor(model => model.LastUpdated)
@Html.LabelFor(model => model.Title)
@Html.EditorFor(model => model.Title)* @Html.ValidationMessageFor(model => model.Title)
@Html.LabelFor(model => model.Content)
@Html.EditorFor(model => model.Content)* @Html.ValidationMessageFor(model => model.Content)
@Html.Label("Categories")
@Html.DropDownList("CategoryList") @Html.ActionLink("Create new", "Create", "Category", new { Id = Model.Id, ReturnAction = "Edit" }, new { })
    @if (!(ViewBag.PostCategories == null)) { foreach (var postCategory in ViewBag.PostCategories) {
  • @postCategory.Name @Html.ActionLink("Remove", "RemoveCategory", new { Id = postCategory.Id, PostId = Model.Id })
  • } }

@Html.ActionLink("Cancel", "Index")

} } else {

You must be an administrator or contributor to view this page and contributors can only edit their own posts.

} @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

The first line strongly-types the View to a Post Model object. In the HTML, the properties of the Post object can be displayed to the user, for example the line �@Html.EditorFor(model => model.Title)*� will generate a textbox to display the Title property of the Post object and allow the user to edit it. ASP.NET MVC will automatically generate code like this for all of the properties in the Model in a process called scaffolding, which can greatly reduce development time.

The Controller

The Controller in ASP.NET MVC is responsible for retrieving Model objects and passing them to Views to provide a user interface. It is also used to also accept new data which has been posted back by users, process it, and use it to update the Model, for example by storing it in a database. An example of Controller code is shown below.


        // GET: /Post/Edit/5



        public ActionResult Edit(int id = 0)

        {

            Post post = db.Posts.Find(id);

            if (post == null)

            {

                return HttpNotFound();

            }

            var categories = GetCategoryDropDown();

            var postCategories = post.Categories.Where(p => p.Id != Constants.CATEGORY_UNCATEGORISED).OrderBy(p => p.Name).ToList();

            foreach (var postCategory in postCategories) // Remove the post's existing categories from the dropdown list

            {

                categories.RemoveAll(p => p.Value == postCategory.Id.ToString());

            }

            ViewBag.CategoryList = categories;

            ViewBag.PostCategories = postCategories;

            return View(post);

        }

This retrieves a Post object from the database, makes some preparations, and then returns a View to which the Post object is strongly-typed. This keeps the retrieval of the data separate from its presentation in the View, providing separation of concerns. In ASP.NET Web Forms, this would need to be combined with the validation and formatting logic in the .aspx.cs code-behind file for each web form.

Conclusion

ASP.NET MVC should be considered as an alternative approach to ASP.NET Web Forms when designing web applications. It provides separation of concerns, encourages compliance with DRY principles and also generates cleaner HTML code without the need for features such as the ViewState. You will need to consider the investment required in learning a new approach before attempting to use it on a large project, however.

View all Informatics Centre blog posts.