Search Sreeni's Insights

Filter by content type
technical November 6, 2012 15 min read

How to build CRUD with Razor views and dependency injection? - Part 6

This article builds the student list, create, edit, details and delete screens with a service layer, view models, validation, Post-Redirect-Get and dependency injection with Unity.

Share:

How to build CRUD with Razor views and dependency injection? - Part 6

Now we have the structure, the entities and the C# features, and it is the time to build the screens which the users really see. The CRUD screens are the part which looks easiest, and also the part where most of the bad habits come in, the controller creates the DbContext, the entity is posted directly from the form, and the validation is only on the client side. In the previous article, we discussed the delegates, lambda expressions, extension methods and events. In this article, we are going to build the student list, create, details, edit and delete screens end to end, with the service layer, the view models, Razor views, the validation and the dependency injection, and we will follow the Post-Redirect-Get flow. Every code block and every screen of this article is from the sample application.

Student Management System series:

  1. How to structure an ASP.NET MVC application? - Part 1
  2. How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
  3. How does routing work, with custom, nested and area routes? - Part 3
  4. How to model the data with Entity Framework and LINQ? - Part 4
  5. How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
  6. How to build CRUD with Razor views and dependency injection? - Part 6 (this article)
  7. How to remove the repeated code with a base controller, base service and base repository? - Part 7
  8. How to build the views with layouts, partial views and HTML helpers? - Part 8
  9. How to use filters, model binding and validation? - Part 9
  10. How to add registration, login, forgot password, change password, profile and logout? - Part 10
  11. How to build a Web API with ASP.NET MVC 4? - Part 11
  12. How to test the application and keep it clean? - Part 12

TL;DR Summary

  • Keep the controller thin. It receives the input, calls the service and chooses the result.
  • Put the application logic in a service, and the data access behind a repository interface and a unit of work.
  • Use a view model for the form, and don’t post the entity directly. It protects us from the over-posting attack.
  • Validate on the server with the data annotations and ModelState.IsValid. The client side validation is only a convenience.
  • Use [ValidateAntiForgeryToken] on every POST action, and a POST (not a GET) for the delete.
  • After a successful POST, redirect (Post-Redirect-Get) so that the refresh doesn’t submit the form again.
  • Inject the dependencies through the constructor, and register them in one place, the composition root.

The service layer

Note: This article shows the first, plain version of the service and the controller, so that the basic flow is easy to see. The sample code has the final version, where the service derives from the BaseService and the controller from the BaseController, which log the work and handle the exceptions. We will refactor to it in Part 7, and the lines which are different (the ILogger parameter, the Execute lambdas) are explained there.

The controller should not know about the repository or the context. It talks to a service, which is in SMS.Services and knows nothing about MVC. First the interfaces, which live in SMS.Domain,

public interface IStudentRepository
{
    IQueryable<Student> GetAll();
    Student Find(int id);
    void Add(Student student);
    void Remove(Student student);
}

public interface IUnitOfWork
{
    void Commit();
}

public interface IStudentService
{
    event EventHandler<StudentEnrolledEventArgs> StudentEnrolled;

    IList<Student> Search(string term, int pageNumber, int pageSize);
    Student Find(int id);
    int Create(Student student);
    void Update(Student student);
    void Delete(int id);
    void Enroll(int studentId, int courseId);
}

And the implementation, in SMS.Services. Each class depends only on the abstractions,

public class StudentService : IStudentService
{
    private readonly IStudentRepository _students;
    private readonly IUnitOfWork _unitOfWork;

    public StudentService(IStudentRepository students, IUnitOfWork unitOfWork)
    {
        _students = students;
        _unitOfWork = unitOfWork;
    }

    public IList<Student> Search(string term, int pageNumber, int pageSize)
    {
        var query = _students.GetAll();

        if (!string.IsNullOrEmpty(term))
            query = query.Where(s => s.LastName.Contains(term));

        return query.OrderBy(s => s.LastName).Page(pageNumber, pageSize).ToList();
    }

    public int Create(Student student)
    {
        student.CreatedOn = DateTime.UtcNow;
        _students.Add(student);
        _unitOfWork.Commit();
        return student.Id;
    }

    public void Update(Student student)
    {
        _unitOfWork.Commit();
    }

    public void Delete(int id)
    {
        var student = _students.Find(id);
        if (student == null)
            return;

        _students.Remove(student);
        _unitOfWork.Commit();
    }

    // Find and Enroll are shown in the previous articles
}

The Page is the extension method we wrote in Part 5, and the query is executed by ToList() inside the service, before the context goes away. The repository and the unit of work are implemented in SMS.Data with the SchoolContext, and the Commit() calls SaveChanges().

Note: The Update only commits. The student which the controller loaded from the same context is already tracked by the context, so the changes in its properties are saved by SaveChanges(). It works because one context is shared for the whole request, and we will see how in the dependency injection section.

The view model

The form doesn’t need all the members of the Student. It doesn’t have the Id or CreatedOn, and the user must not be able to set them. So we create a class only for this screen. The same class is used by the create and the edit screens,

public class StudentFormModel
{
    [Required, StringLength(50)]
    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Required, StringLength(50)]
    [Display(Name = "Last name")]
    public string LastName { get; set; }

    [Required, EmailAddress]
    public string Email { get; set; }

    [Required, DataType(DataType.Date), MinimumAge(16)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date of birth")]
    public DateTime DateOfBirth { get; set; }
}

Must Be Aware: If we bind the Student entity directly to the form, a malicious user can add one more field to the post, like IsActive=true or Id=7, and the model binder will set it (the over-posting or mass assignment). A view model has only the fields which the form shows, so there is nothing extra to set.

The data annotations are used by the server side validation, and by the client side validation also when the jQuery validation scripts are included. The server side check is the one which counts, a user can disable the JavaScript. The [MinimumAge(16)] is our own validation attribute, we will write it in Part 9. The [EmailAddress] attribute is available from the .NET Framework 4.5, on 4.0 use a [RegularExpression] instead.

The controller

The controller of our sample has the action methods of the CRUD, and each of them is only a few lines. It receives the ICatalogService also, for the list of the courses which we need in Part 8. We will go through them with the screens, one by one.

public class StudentsController : Controller
{
    public const int PageSize = 5;

    private readonly IStudentService _service;
    private readonly ICatalogService _catalog;

    public StudentsController(IStudentService service, ICatalogService catalog)
    {
        _service = service;
        _catalog = catalog;
    }

    // actions ...
}

Read - the list and the details

public ActionResult Index(StudentSearchModel search)
{
    ViewBag.Term = search.Term;
    ViewBag.Page = search.Page;
    ViewBag.PageSize = PageSize;

    var students = _service.Search(search.Term, search.Page, PageSize);
    return View(students);
}

public ActionResult Details(int id)
{
    var student = _service.Find(id);
    if (student == null)
        return HttpNotFound();

    return View(BuildDetailsModel(student));
}

The StudentSearchModel is a small class with the Term and the Page properties (the page is 1 by default). The model binder fills it from the query string, /Students?term=Ra&page=2, and we will see how in Part 9. The BuildDetailsModel prepares the model of the details view, which also has the courses for the enroll list, and we will see it in Part 8. For an id which does not exist we return the 404 and not an exception.

The Index view shows the list, the search box and the paging links,

@model IList<Student>
@{
    ViewBag.Title = "Students";
    int page = ViewBag.Page;
    int pageSize = ViewBag.PageSize;
}

<h2>Students</h2>

@if (TempData["Message"] != null)
{
    <p class="message">@TempData["Message"]</p>
}

@Html.Action("Summary")

<div class="toolbar">
    @using (Html.BeginForm("Index", "Students", FormMethod.Get))
    {
        <input type="text" name="term" value="@ViewBag.Term" placeholder="Search by last name" />
        <input type="submit" value="Search" />
    }
    @Html.ActionLink("Add a student", "Create", null, new { @class = "button" })
</div>

<table>
    <tr><th>Name</th><th>Email</th><th>Date of birth</th><th></th></tr>
    @foreach (var student in Model)
    {
        <tr>
            <td>@student.FullName()</td>
            <td>@student.Email</td>
            <td>@Html.DisplayFor(m => student.DateOfBirth)</td>
            <td>
                @Html.ActionLink("Details", "Details", new { id = student.Id }) |
                @Html.ActionLink("Edit", "Edit", new { id = student.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = student.Id })
            </td>
        </tr>
    }
</table>

@Html.PagerLinks(page, Model.Count == pageSize, p => Url.Action("Index", new { term = ViewBag.Term, page = p }))

The FullName() is the extension method of Part 5, so the namespace of the extension class (SMS.Domain) is imported for all views in the Views/Web.config. The Html.Action("Summary"), the DisplayFor and the PagerLinks are the child action, the display template and the custom HTML helper, and all of them are explained in Part 8. This is the screen,

The student list screen
The student list screen

Note: The “Next” link is shown when the page is full. It is the simple way, and it shows one extra empty page when the number of students is an exact multiple of the page size. If it is not acceptable, the service can return the total count also, and the view can calculate the number of pages.

The details screen shows the data of the student and the courses, and it has the enroll form. We will build it in Part 8,

The student details screen
The student details screen

Create - the Post-Redirect-Get flow

The following diagram shows the flow of the create screen. The purple path is the successful one.

Create student flow with Post-Redirect-Get
Create student flow with Post-Redirect-Get
public ActionResult Create()
{
    return View(new StudentFormModel { DateOfBirth = DateTime.Today.AddYears(-18) });
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentFormModel model)
{
    if (!ModelState.IsValid)
        return View(model);

    var student = new Student
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        Email = model.Email,
        DateOfBirth = model.DateOfBirth,
        IsActive = true
    };

    _service.Create(student);
    TempData["Message"] = "Student created";
    return RedirectToAction("Index");
}

There are two Create actions with the same name. The first one answers the GET and shows the empty form, and the second one is marked [HttpPost] and receives the form. The form is the same for the create and the edit screens, so it is a partial view, _Form.cshtml, which both of them use,

@model StudentFormModel

@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<div class="field">
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(m => m.FirstName)
</div>

<div class="field">
    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)
    @Html.ValidationMessageFor(m => m.LastName)
</div>

<div class="field">
    @Html.LabelFor(m => m.Email)
    @Html.TextBoxFor(m => m.Email)
    @Html.ValidationMessageFor(m => m.Email)
</div>

<div class="field">
    @Html.LabelFor(m => m.DateOfBirth)
    @Html.TextBoxFor(m => m.DateOfBirth, "{0:yyyy-MM-dd}", new { type = "date" })
    @Html.ValidationMessageFor(m => m.DateOfBirth)
</div>

And the Create view,

@model StudentFormModel
@{
    ViewBag.Title = "Add a student";
}

<h2>Add a student</h2>

@using (Html.BeginForm())
{
    @Html.Partial("_Form")
    <input type="submit" value="Create" />
    @Html.ActionLink("Cancel", "Index", null, new { @class = "button secondary" })
}

@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}

The TextBoxFor(m => m.FirstName) is a lambda expression again. It gives the helper the property name, so the name and id of the field, the value, the label and the validation message are all generated from the model. Rename the property, and the compiler finds every place. The AntiForgeryToken() writes a hidden field which the [ValidateAntiForgeryToken] attribute checks, so a form posted from another site is rejected. The jQuery validation scripts are added only to the pages which have a form, with the Scripts section of the layout. This is the empty form,

The create student form
The create student form

When the model is not valid, we return the same view with the same model, and the form shows the entered values with the errors, so the user doesn’t type everything again. The following screen was taken with the JavaScript disabled, to prove that the server side validation works alone,

The server side validation errors
The server side validation errors

When it is valid, we save, and we redirect. This is the Post-Redirect-Get pattern. If we returned the view directly after the POST, the refresh of the browser would submit the same form again and create a duplicate student. TempData keeps the message for the next request only, so the Index page shows it once,

The student created message
The student created message

Update - the edit screen

public ActionResult Edit(int id)
{
    var student = _service.Find(id);
    if (student == null)
        return HttpNotFound();

    return View(new StudentFormModel
    {
        FirstName = student.FirstName,
        LastName = student.LastName,
        Email = student.Email,
        DateOfBirth = student.DateOfBirth
    });
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, StudentFormModel model)
{
    var student = _service.Find(id);
    if (student == null)
        return HttpNotFound();

    if (!ModelState.IsValid)
        return View(model);

    student.FirstName = model.FirstName;
    student.LastName = model.LastName;
    student.Email = model.Email;
    student.DateOfBirth = model.DateOfBirth;

    _service.Update(student);
    TempData["Message"] = "Student updated";
    return RedirectToAction("Details", new { id = id });
}

The GET action fills the view model from the student, and the same partial view shows it. The POST action loads the student again, copies the fields of the view model and saves. We don’t take the student from the form, so the user can’t change anything which is not in the view model. The id comes from the URL, /Students/Edit/1, and the Html.BeginForm() posts to the same URL.

The edit student form
The edit student form

Must Consider: The copy of the fields from the view model to the entity is a boring code. For two or three screens it is fine (KISS). When it becomes many, a mapping helper or an extension method (like ToEntity()) removes the repetition, but don’t hide it so deep that nobody can see what is set.

Delete - ask first, then POST

public ActionResult Delete(int id)
{
    var student = _service.Find(id);
    if (student == null)
        return HttpNotFound();

    return View(student);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    _service.Delete(id);
    TempData["Message"] = "Student deleted";
    return RedirectToAction("Index");
}

The delete is never done by a GET request. A GET must be safe, otherwise a search engine, a browser pre-fetch or a link in an email can delete the data. The GET action only shows the confirmation screen, and the real delete is a POST with the anti-forgery token. Because a method can’t have the same name and the same parameters as another, the POST one is called DeleteConfirmed and the [ActionName("Delete")] attribute keeps the action name as Delete.

The delete confirmation screen
The delete confirmation screen

After the delete, we redirect to the list with the message,

The student deleted message
The student deleted message

Dependency injection

The StudentsController has no default constructor, it needs an IStudentService. The controller factory (Part 2) asks the IDependencyResolver, and we give it an IoC container. The following diagram shows what the container builds for one request.

Object graph built by the IoC container for one request
Object graph built by the IoC container for one request

The registrations are written in one place, the composition root of SMS.Web, which is the only code allowed to know the concrete classes,

public static class Bootstrapper
{
    public static IUnityContainer Build()
    {
        var container = new UnityContainer();

        container.RegisterInstance<ILogger>(new TraceLogger());
        container.RegisterType<SchoolContext>(new HierarchicalLifetimeManager());
        container.RegisterType<IStudentRepository, StudentRepository>();
        container.RegisterType<IDepartmentRepository, DepartmentRepository>();
        container.RegisterType<ICourseRepository, CourseRepository>();
        container.RegisterType<IUnitOfWork, UnitOfWork>();
        container.RegisterType<IStudentService, StudentService>();
        container.RegisterType<ICatalogService, CatalogService>();

        return container;
    }
}

The SchoolContext is registered with the HierarchicalLifetimeManager. It means one instance for each child container, and we create one child container for each web request. So the repository and the unit of work receive the same context, and the Commit() saves the changes which the repository made. Find below the resolver which connects the Unity to MVC,

public class UnityDependencyResolver : System.Web.Mvc.IDependencyResolver
{
    private const string Key = "UnityChildContainer";
    private readonly IUnityContainer _root;

    public UnityDependencyResolver(IUnityContainer root)
    {
        _root = root;
    }

    private IUnityContainer CurrentContainer
    {
        get
        {
            var items = HttpContext.Current.Items;
            var child = items[Key] as IUnityContainer;
            if (child == null)
            {
                child = _root.CreateChildContainer();
                items[Key] = child;
            }
            return child;
        }
    }

    public object GetService(Type serviceType)
    {
        try { return CurrentContainer.Resolve(serviceType); }
        catch (ResolutionFailedException) { return null; }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try { return CurrentContainer.ResolveAll(serviceType); }
        catch (ResolutionFailedException) { return new object[0]; }
    }

    public static void DisposeCurrentRequestContainer()
    {
        var child = HttpContext.Current.Items[Key] as IUnityContainer;
        if (child != null)
            child.Dispose();
    }
}

MVC asks the resolver for many types, and it expects a null when we can’t provide one, so the exception of Unity is converted to null. The child container is kept in HttpContext.Items, which lives for one request. Finally the Global.asax.cs connects everything. The end of the request disposes the child container, and it disposes the context also. The lines for the areas, the Web API and the filters are explained in Part 3, Part 11 and Part 9. Note the order, the Web API route is registered before the MVC routes,

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        var container = Bootstrapper.Build();

        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new UnityWebApiDependencyResolver(container);
    }

    protected void Application_EndRequest()
    {
        UnityDependencyResolver.DisposeCurrentRequestContainer();
    }
}

Note: There are NuGet packages which do the same, like Unity.Mvc3, and Ninject has the InRequestScope(). Writing it once by hand shows what these packages do, and it is not more than fifty lines. The Web API has its own resolver interface, and we will write it in Part 11.

Note: A controller with many constructor parameters is a warning that it does too much (Single Responsibility Principle). Split it by the feature, don’t hide the problem behind a container.

Wrap up

In this article, we have looked at how to build the list, details, create, edit and delete screens, with the service layer, the view model, the server side validation, the anti-forgery token, the Post-Redirect-Get pattern and the dependency injection, and we have seen the real screens of the application. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to test all of this, with the unit tests and the integration tests, and a summary of the whole series.

Related Posts