Highlights of ASP.NET MVC 3 (Cont.)
Saving and Retrieving Entries
The first step to doing anything with data is to add a data access capability. To keep the project simple, I will not break up the solution into multiple projects, but it would be normal to do so. I will add a new interface to the project.public interface IEntryRepository
void Save(Entry entry);
With this interface, we can support all the necessary operations to run our application. We’ll add the other capabilities, and we will have a screen similar to the one in Figure 6.
Figure 6: We can now retrieve all guestbook entries.
As ASP.NET MVC 3 is fleshed out more, it will be easy to hook up an IoC container to enable the controller to require our data access interface, but for now, we will add an additional constructor to resolve the concrete class. I expect a future preview to make this feature very easy to hook up. The full controller code can be seen in Listing 3. The constructors are shown here.private IEntryRepository _repository;
public HomeController(IEntryRepository repository)
_repository = repository;
public HomeController() : this(new
When we hook up MVC 3 Service Location, we will be able to remove the need for the parameterless constructor and have the IoC container of choice resolve the concrete class for us. Brad Wilson has already published a tutorial and sample on this at http://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html.
Now that we have some way to retrieve all the entries, we need to send them to the view. Adding a quick filter to the controller does that for us since we need the entries both on the GET request as well as the POST.protected override void OnActionExecuted(
Entry allEntries = _repository.GetAll();
ViewModel.Entries = allEntries;
Using our repository and the dynamic property, ViewModel, we have added an array of Entry(s). At the bottom of our view, Index.cshtml, we can add a single line to pave the way to displaying the entries.@Html.Partial("entries",
This uses the Razor syntax with the existing HTML helper. Because the existing helper requires an object type, we can’t pass in a generic expression directly, so we have cast it to a known type. Helpers that support dynamic types are probably needed before the final release to keep this ugly code from being necessary.
If we move over to our partial view, we see that we have designed it using the Web Forms view style. You can see the full view in Listing 4, but just to demonstrate that different view types can be mixed and matched, we use the good old DataGrid.<script runat="server" language="C#">
protected override void OnLoad(EventArgs e)
grid.DataSource = (Entry)Model;
<asp:DataGrid ID="grid" runat="server"
We do have to cast the Model property to a known type. I considered using a strongly typed view here, but that mechanism doesn’t allow for polymorphism of enumerable types because of a type check. Perhaps this will change in the future.
Now that we have our guestbook entries showing up on the screen, let’s add our business rule.
A common business rule is ensuring against duplicates. Whether it be adding users to a system where the user name is unique or ensuring that no product codes are reused.
In our case, we don’t want our guestbook to be cluttered with duplicate entries, intentional or not. The goal is represented in Figure 7.
Figure 7: An entry with the same name and message is rejected.
In order to accomplish this, we will use a new feature of ASP.NET MVC, IValidateObject integration. The definition of this interface is as follows.namespace System.ComponentModel.DataAnnotations
public interface IValidatableObject
Notice that this is an existing interface from the DataAnnotations namespace. MVC 3 adds support for using this interface. When the model object implements this interface, the Validate method will be executed. You can implement this interface directly on the Entry class if you like, but in real applications, there never tends to be just one business rule, so we will use polymorphism to layer on the business rule mechanism to our Entry class. I have defined a class called EntryWithBusinessRules. You can see this in Listing 5. The meat of the logic is inside the Validate method here.IEnumerable<Entry> matches = _repository.GetAll()
.Where(entry => entry.Name.Equals(this.Name))
if(matches.Count() > 0)
yield return new ValidationResult(
"This is a duplicate message.");
To prevent duplicates, we needed the repository, so we will benefit in the future from the Service Location support here as well. Regardless if the implementation can be made more efficient, and it can, this code adds an error if a match is found. This message is floated all the way up through model state and into the ValidationSummary in our view.
You can imagine the scenarios afforded by this mechanism because it gives a powerful hook to even funnel validation out to an external rules engine.
The last enhancement we will make to the guestbook application is for operations and tuning support. We will add a global filter, another new capability of MVC 3, to write messages to the HTTP trace so that we can see timings of each step.