Now that we have gotten familiar with the principles of
controller classes, action methods and action parameters, we can apply them in
KBlog to update our code.
For KBlog we need three controllers (regarding that here we
just want to build a very simple blogging engine to show some concepts):
·
Controller for homepage which is our index: We load data for
recent N posts and the list of all categories.
·
Controller for individual posts: We load data for a specific post
based on its ID.
·
Controller for individual categories: We load all posts that are
in a specified category based on its unique name.
Listing 7 is the code for the homepage in HomeController where we do not need to pass any parameter.
Later I will update this controller to load recent posts and all categories and
pass them to the appropriate view. For now, just focus on the controller part
of the code.
Listing 7:
using System;
using System.Web;
using System.Web.Mvc;
namespace KBlog.Controllers
{
public class HomeController : Controller
{
// Sample URL: /Default.aspx
[ControllerAction]
public void Index()
{
}
}
}
The other controller is PostsController
where we handle requests for individual posts based on the unique ID (Listing
8). Note that later we need to modify the default routing definitions in order
to route request to this controller.
Listing 8:
using System;
using System.Web;
using System.Web.Mvc;
namespace KBlog.Controllers
{
public class PostsController : Controller
{
// Sample URL: /Post/25
[ControllerAction]
public void Post(int id)
{
}
}
}
And the last controller is CategoriesController
where we handle requests for a specific category based on its unique string
name and load all posts in that category (Listing 9). Like PostsController
we need to modify default routing definition in order to route requests to this
controller.
Listing 9:
using System;
using System.Web;
using System.Web.Mvc;
namespace KBlog.Controllers
{
public class CategoriesController : Controller
{
// Sample URL: /Category/DotNet
[ControllerAction]
public void Category(string name)
{
}
}
}