Kentico CMS 7.0 Developer's Guide

MVC development overview

MVC development overview

Previous topic Next topic Mail us feedback on this topic!  

MVC development overview

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

Kentico CMS supports website development using ASP.NET MVC. You can find an example of a page developed using the MVC development model in the Examples/Development-models/MVC section of the sample Corporate Site.

 

Document configuration

 

The document uses an MVC type page template, which specifies the default controller, as well as the action that is executed when the page is viewed. If you edit the document on the Properties -> Template tab and click the EditTemplateProperties Edit template properties button, you can see the configuration of the page's template as shown below:

 

Default controller - sets the name of the controller class containing the MVC action that should be performed when pages using the template are accessed (without the Controller part at the end). For example, if the class is called NewsMVCController, enter NewsMVC. The system first searches for the specified class in the CMS.Controllers.<current site code name> namespace. If it is not found there, the CMS.Controllers.Global namespace is searched.

Default action - specifies the exact action defined within the controller class that is performed when pages based on this template are loaded.

 

devguide_clip2063

 

Close the template editing dialog and open the document's Properties -> URLs tab. In this case, the page's URL is defined as an ASP.NET Route, but the standard alias path reflecting the document's position in the content tree can also be used for MVC pages as long as they use the appropriate template type.

 

devguide_clip1804

 

The document has a registered document alias, which handles the /NewsMVC/Detail/{id} pattern. If you edit (Edit) the alias, you can see that its Default controller is set to NewsMVC and the Default action is Detail. These will be used instead of the default template configuration when the page is accessed through the alias URL.

 

devguide_clip1806

 

Further advanced options are also available for MVC URL patterns:

 

{controller}, {action} - allows you to specify controllers and actions dynamically through URL parameters. For example, the /{controller}/{action}/{id} pattern provides the same controller, action and page output as the example above when the /NewsMVC/Detail/My-First-News URL is accessed. However, it could also be used to direct the users to pages generated by other controllers or actions (the parameter parts of the URL may vary).

{name;value} - provides a way to set the default value of the parameters in the URL path. For example, /{controller;NewsMVC}/{action;Detail}/{id;My-First-News} has the same functionality as the previous option, but the system is able to automatically generate the default URL /NewsMVC/Detail/My-First-News for the document if the parameters are not specified.

{*name;value*} - hidden value, which is passed as a parameter to the action handler in the controller class, but is not incorporated into the URL itself. For example, /NewsMVC/List{*TopN;10*} generates the /NewsMVC/List pattern and provides the value of the TopN parameter during the processing of the request. Note that the TOP N functionality is not implemented in the sample controller and you need to handle it in the code if you want to try it. The URL of the page will still be the same as before (the parameter is hidden). This way, the pages can be parametrized by the developer even if they use the same controller and action.

 

 

InfoBox_Tip

 

Using MVC views in editing mode

 

To configure documents to show the MVC view in editing mode (i.e. when working with documents on the Page tab of CMS Desk), enable the Use live URL for editing modes setting in Site Manager -> Settings -> Content -> Content management.

 

You do not need to enable this setting if your documents are based on MVC type page templates, which automatically use the MVC view in editing mode.

 

 

MVC code files

 

The NewsMVC controller specified in the Default controller field above is physically located in ~\App_Code\Controllers\Global\NewsMVCController.cs (or ~\Controllers\Global\NewsMVCController.cs. if you installed Kentico CMS as a web application). The List action specified in the Default action field of the sample page's template is implemented in its code, along with the Detail action, which is used when the page is accessed through the document alias URL. The following is the full code of the controller class:

 

using System.Data;
using System.Web.Mvc;

 
using CMS.CMSHelper;
using CMS.DocumentEngine;
using CMS.URLRewritingEngine;

 
namespace CMS.Controllers.Global
{
  /// <summary>
  /// Sample controller for the news.
  /// </summary>
  public class NewsMVCController : Controller
   {
      /// <summary>
      /// Processes the detail action.
      /// </summary>
      public ActionResult Detail()
       {
          // Prepares the data for the view.
          TreeNode document = TreeHelper.GetDocument(CMSContext.CurrentSiteName, "/News/" + RouteData.Values["id"], CMSContext.PreferredCultureCode, true, "CMS.News", true);
          if (document != null)
           {
               document.SetValue("NewsTitle", document.GetValue("NewsTitle"));
               ViewData["Document"] = document;
           }
          else
           {
              // Return a page not found error if the document does not exist.
              URLRewriter.PageNotFound();
              return null;
           }

 
          return View();
       }

 
      /// <summary>
      /// Processes the list action.
      /// </summary>
      public ActionResult List()
       {
          // Prepares the data for the view.
          var documents = TreeHelper.GetDocuments(CMSContext.CurrentSiteName, "/News/%", CMSContext.PreferredCultureCode, true, "CMS.News", null, "NewsReleaseDate DESC", -1, true, 0);
          if (documents != null)
           {
               ViewData["NewsList"] = documents;
           }

 
          return View();
       }
   }
}

 

The views that display the pages when the respective actions are performed are located under ~\Views\Global\NewsMVC\. The following code is the full code of the Detail.aspx file of the Detail view:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detail.aspx.cs" Inherits="Views_Global_NewsMVC_Detail" MasterPageFile="Root.master" %>

 
<asp:Content ID="cntMain" ContentPlaceHolderID="plcMain" runat="Server">
  <div class="innerContent">
      <h1>
           MVC Example</h1>
      <p>
           This is a sample for the page rendered by MVC. It displays the news detail. The detail is provided by <strong>NewsMVC</strong> controller and <strong>~/Views/Global/NewsMVC/Detail.aspx</strong> view and routed through MVC URL pattern <strong>/NewsMVC/Detail/{id}</strong> added as document alias to the same document as the main document. This way, there is no need to provide separate documents for detail view.
      </p>
      <div class="LightGradientBox ">
          <h2>
              <%=Document.GetValue("NewsTitle")%></h2>
          <p>
              <%=Document.GetValue("NewsText")%></p>
          <p>
              <a href="<%=ResolveUrl("~/newsmvc/list/")%>">Back to the list of news</a>
          </p>
      </div>
  </div>
  </div>
</asp:Content>

 

And the following code is the full code of its Detail.aspx.cs code behind file:

 

using System;
using System.Data;
using System.Web.Mvc;

 
using CMS.DocumentEngine;

 
/// <summary>
/// Sample view for the news.
/// </summary>
public partial class Views_Global_NewsMVC_Detail : ViewPage
{
  /// <summary>
  /// Returns the displayed document
  /// </summary>
  public TreeNode Document
   {
      get
       {
          return (TreeNode)ViewData["Document"];
       }
   }
}

 

How it works on the live site

 

When you navigate to the page on the live site, you can initially see the list mode view, which is specified as the default option for the page's template (the List action from the NewsMVC controller is executed). It displays a list of all news items from the News section, as can be seen in the screenshot below.

 

devguide_clip1803

 

The titles of the news items contain links to the /NewsMVC/Detail/{id} URL, where the {id} wildcard parameter is substituted by the alias of the corresponding news document. If you click it, the Detail action of the NewsMVC controller is executed, which displays a detail of the given news item. This is all handled by a single document, the different content is ensured through the special document alias URL, which triggers the detail view.

 

devguide_clip1807