Create a Book widget
The following tutorial demonstrates how to create a simple MVC Books widget. You leverage the attribute routing of MVC 5 in the context of a Sitefinity CMS widget. The Books widget displays a list of books on the frontend and tracks on the client the points retrieved for each book.
Install the Books widget
- Clone the MVC samples repository.
- Build the
BooksWidget project, located in the AttributeRouting sample.
- Reference the
BookWidget.dll from your Sitefinity web application.
Create the Books widget
Sitefinity CMS makes it possible to have MVC widgets that are stored in separate assemblies. The following sample creates the Books widget in a separate assembly.
Perform the following:
- Create a new class library named
- In Visual Studio, in the Package Manager Console, make sure
BooksWidget project is selected as default project.
Install the required packages:
- Modify the
AssemblyInfo.cs by adding the following code:
- Create the following folders:
Create the model classes
MVC/Models folder, create a new class named
Book. The class needs to have:
Vote method to increment the points
Book class should look similar to the following:
Next, in the
MVC/Models folder, you create a new class named
BooksViewModel. The class needs to have the following properties:
BooksViewModel class should look similar to the following:
Create the controller
Perform the following:
- In folder
MVC/Controllers, create a new class that derives from the
System.Web.Mvc.Controller class and name it
- Add the fields to the
- Create an
Index action with route relative to the current page. The action accepts the page number as an argument.
Vote actions with a direct route, so that they can be accessed with AJAX calls.
- Add a
ControllerToolboxItem attribute to the
Thus, Sitefinity CMS automatically adds the Books widget in the toolbox.
Use the following code sample:
Create the view
You need to create an
Index view, because this is the only view that is used by the
BooksController. To do this, you must create a new Razor view named
Index and to place it in the
To create the Index view, use the following code:
NOTE: You can create a Razor view in a class library project by selecting HTML Page from the Add New Item dialog, and then renaming the file extension to
.cshtml. In the file properties, set the view as Embedded Resource.
Create the client-side script
books-widget.js. This script will retrieve and update the books' points calling the JSON actions:
NOTE: Be sure to mark the script as an Embedded Resource in the file properties.
You can now build the project and test the result by placing the Books widget on a page.