POCO controllers in ASP.NET vNext

November 10, 2014 by Anuraj

.Net ASP.Net ASP.Net MVC

As part of ASP.NET MVC 6, Microsoft introduced POCO(Plain Old CLR Object) Controllers. Unlike MVC 5 or previous versions of MVC, POCO contollers, has no base class, no need to implement any interface, it is 100% convention.

POCO controller implementation.

using Microsoft.AspNet.Mvc;

public class HomeController
{
	public ActionResult Index()
	{
		return new ViewResult() { ViewName = "Index" };
	}
}

As long as your class is public, non-abstract, has a Controller suffix and is defined in an assembly that references any of the MVC assemblies (Microsoft.AspNet.Mvc.Core, Microsoft.AspNet.Mvc etc), it will be discovered as a valid controller.

Injecting services

using Microsoft.AspNet.Mvc;
public class HomeController
{
    [Activate]
    public ViewDataDictionary ViewData { get; set; }

    public ActionResult Index()
    {
        return new ViewResult() { ViewData = ViewData };
    }
}

The Activate attribute will help ASP.Net runtime to inject various services to the controller. You can use ViewDataDictionary.Model property for passing Model to view in POCO controllers.

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub