In the last entry, we created designed our controller through a test:
[Test]
public void SuccessfulIndex()
{
GivenController.As<UserController>()
.ShouldRenderItself(RestfulAction.Index)
.WhenCalling(x => x.Index());
}
Now, we need to code this:
A Fluent Controlller in action
In fact, to make test run above, you need to do nothing else than inherit from the AbstractRestfulFluentController.
using MvcContrib.FluentController;
public class UserController : AbstractRestfulFluentController
{
public ActionResult Index()
{
return View();
}
}
Let’s now look at how to create a skinny controller. Let’s take a redirection design:
GivenController.As<UserController>()
.ShouldRedirectTo(RestfulAction.Index)
.IfCallSucceeds()
.WhenCalling(x => x.Create(null));
Here’s the controller code we need:
public ActionResult Create(object model)
{
return CheckValidCall()
.Valid(x => RedirectToAction(RestfulAction.Index))
.Invalid(() => View("New", model));
}
A more complex example of Create is where it calls a repository. Here if the Repository throws an exception it will execute .Invalid otherwise it will execute .Valid.
public ActionResult Create(object model)
{
return CheckValidCall(() => UserRepository.Create(model))
.Valid(x => View(RestfulAction.New, x))
.Invalid(() => RedirectToAction(RestfulAction.Index));
}
So far you have seen two fluent controller actions available, however, also available are:
- InvalidNoNewErrors
- Other
And within the context of CheckValidCall you also get access:
- controller
- model
- isValid
- newErrors
Another feature to be aware of is that you can create own extensions. The current CheckValidCall returns a FluentControllerAction<T> so all you have to do is create an extension on this as you would with an extension method. You can even rewrite the CheckValidCall and create your own one.
Post a Comment