Archive for the ‘C#’ Category

The documentation for Sitefinity is a bit… hit or miss. Some of the newer features, such as the Fluent API, simply do not have enough examples / documentation available to be able to work out of the gate. Such was the case with my task for today: adding a custom module’s widgets into the Siteifinty install’s toolbox.

First of all, create your Resource class. I created this a the root of my project, in the same folder as the ContentModuleBase class. This class will contain, among other things, all of the friendly names and descriptions that your widget will use:

In a recent project, one of my models had the following validation requirements:
If “CompletedDate” has a value (a date value), “Status” must be set to “Completed”. If “Status” is set to “Completed”, the “CompletedDate” must be set.

In other words, validation wasn’t simply that a value must be a string, or a number between x and y, etc; the validation of one field is dependant on the value in the other and vice versa.

This was pretty good, but the problem is *when* the validation occurs when using this approach: when the model is being saved. I want validation to run *before* saving the data, so that MVC can know that there’s a problem, and send some friendly message to the user. A typical “edit” command in a controller looks like this:

So I *do* have an option, I could put a try around db.SaveChanges, and catch my validation error there. However, I would then have to grab the error message and figure out some way to send that back to the client (via ViewBag, most likely). I didn’t like this.

I then inspected this ModelState.IsValid method, and had the thought to create an extension method along the lines of ModelState.IsValidProjectTask(). With this, I can add error messages into the ModelState, specific to the fields. This means Razor script like: