Displaying the page content
This page is a part of a tutorial, which you should follow sequentially, from the beginning to the end. Go to the first page: Getting started with Kentico.
In the previous step of the tutorial, you have created the basic layout and added styling for your website. In this step, you will finally see what the content stored in Kentico looks like on the live site. You now need to roll up your sleeves and write the code of your MVC application.
You will learn about:
- Retrieving the content of pages on MVC sites
- Developing the Home page
- Developing the Medical center page
Retrieving the content of pages on MVC sites
The dynamic content of your website’s pages is created and maintained in the Kentico administration interface, and stored within the database that is shared with your MVC application. To display the data on the live site, you need to write code that retrieves the data, prepare controllers that handle the appropriate URL routes, and create views that format the data into the required HTML output.
We recommend using the strongly-typed classes that you generated for your page types to retrieve page content. In this tutorial, we will use the generated provider to retrieve the latest published versions of pages. However, on more advanced websites, you can also retrieve the current edited version of pages under workflow (before they are published to the live site), and use the data for the content displayed in preview mode. This helps website editors see what their edits look like before publishing.
Well-crafted MVC applications are known for their good performance. With Kentico, the separation of concerns typical for the MVC development pattern is reinforced by the fact that all content editing occurs in a separate application. To keep the site’s performance optimal, we strongly recommend that you carefully adjust all data retrieval API calls to only load the data columns that you pass and display in the corresponding views.
Developing the Home page
To display your website’s Home page, you will create a controller class and an appropriate view. Additionally, you will use a view model class to pass page data from the controller to the view. See the comments in the code blocks for more detailed information about the implementation.
Creating the Home view model
In Visual Studio, create a new Home subfolder in the Models folder.
Select the Home subfolder and add a new HomeViewModel class.
Define the view model properties and their mappings using the following code:
using CMS.DocumentEngine.Types.MEDIO; namespace MEDIOClinic.Models { public class HomeViewModel { // Defines the properties of the Home view model public string DocumentName { get; } public string HomeHeader { get; } public string HomeTextHeading { get; } public string HomeText { get; } // Maps the data from the Home page type's fields to the view model properties public HomeViewModel(Home homePage) { DocumentName = homePage.DocumentName; HomeHeader = homePage.Fields.Header; HomeTextHeading = homePage.Fields.TextHeading; HomeText = homePage.Fields.Text; } } }
Save your changes.
Modifying the Home controller
In the Controllers folder, open the HomeController class.
Replace the default code with the following:
using System.Web.Mvc; using CMS.DocumentEngine.Types.MEDIO; using CMS.SiteProvider; using Kentico.PageBuilder.Web.Mvc; using Kentico.Web.Mvc; using MEDIOClinic.Models; namespace MEDIOClinic.Controllers { public class HomeController : Controller { // GET: Loads and displays the site's Home page public ActionResult Index() { // Retrieves the Home page using the 'GetHome' method from the page type's generated provider Home homeNode = HomeProvider.GetHome("/Home", "en-us", SiteContext.CurrentSiteName) .Columns("DocumentName", "DocumentID", "HomeHeader", "HomeTextHeading", "HomeText"); // Returns a 404 error if retrieval is unsuccessful if (homeNode == null) { return HttpNotFound(); } // Creates a new HomeViewModel instance based on the page data var homeModel = new HomeViewModel(homeNode); // Initializes the page builder with the DocumentID of the page HttpContext.Kentico().PageBuilder().Initialize(homeNode.DocumentID); return View(homeModel); } } }
Save your changes.
The generated provider classes offer several methods you can use to retrieve the data of content-only pages. To get a specific page, we recommend using the node alias path (/Home in the example above), which corresponds with the structure of the site’s content tree in the Pages application. Alternatively, you can also use the Node ID or Node GUID identifiers, which you can find on the General tab in the Pages application.
Updating the Home view
Now you need to format the content of the Home page in a view corresponding to the Index action of the HomeController:
Open the Views/Home/Index.cshtml view file.
Directly under the using statements, add the @model directive referencing the HomeViewModel class created earlier
@model MEDIOClinic.Models.HomeViewModel
Set the ViewBag.Title value to the model’s DocumentName property:
@{ ViewBag.Title = Model.DocumentName; }
Call the Html.Kentico().PageBuilderStyles() and Html.Kentico().PageBuilderScripts within the corresponding Razor sections (as defined in the site’s _Layout). The methods render links to stylesheets and scripts required for the page builder functionality.
@section styles { @* Includes stylesheets necessary for page builder functionality *@ @Html.Kentico().PageBuilderStyles() } @section scripts { @* Includes scripts necessary for page builder functionality *@ @Html.Kentico().PageBuilderScripts() }
From the index.html file in the tutorial resources, copy the HTML code of the two <section> elements in the body tag (styled with the teaser and content CSS classes) to the Home view. Replace the existing placeholder message and commented code.
In the teaser section, replace the text of the paragraph element with the Model.HomeHeader property.
In the content section, replace the following values:
- The text of the heading element with the Model.HomeTextHeading property.
- The text of the paragraph element with the Model.HomeText property.
Call the Html.Kentico().EditableArea extension method with “editableArea” as a parameter inside the content section’s first <div> element.
Editable areas serve as containers for page builder widgets. Each editable area must be defined with a string identifier that is unique within the context of the given view (editableArea in this case).
@Html.Kentico().EditableArea("editableArea")
Save your changes.
The final code of your Home view should look like this:
@using Kentico.Web.Mvc
@using Kentico.PageBuilder.Web.Mvc
@model MEDIOClinic.Models.HomeViewModel
@{
ViewBag.Title = Model.DocumentName;
}
@section styles
{
@* Includes stylesheets necessary for page builder functionality *@
@Html.Kentico().PageBuilderStyles()
}
@section scripts
{
@* Includes scripts necessary for page builder functionality *@
@Html.Kentico().PageBuilderScripts()
}
<section class="teaser">
<div class="col-sm-offset-3 col-sm-4">
<p>@Model.HomeHeader</p>
</div>
<div class="clearfix"></div>
</section>
<section class="content">
<div class="col-sm-offset-3 col-sm-5">
<h1>@Model.HomeTextHeading</h1>
<p>@Model.HomeText</p>
@* Inserts a page builder editable area, allowing modular content composition using widgets *@
@Html.Kentico().EditableArea("editableArea")
</div>
<div class="clearfix"></div>
</section>
Previewing your website’s Home page
Your code retrieves data from the Kentico site and displays it on the live site. Let’s Build your project and see how the page looks!
When you navigate to your website’s URL (e.g., http://localhost/Kentico12_MEDIOClinic), the default {controller}/{action}/{id} route mapped in the project’s RouteConfig targets the Home controller’s Index action and displays your Home page as the website’s root page.
You can also preview the page directly in the Kentico administration interface (e.g., http://localhost/Kentico12_Admin). Switch to the Pages application and select the Preview mode.
The preview feature works because you have the builder.UsePreview feature enabled in your MVC project’s ApplicationConfig class, and the Home page type has the /Home URL pattern matching the route of your Home controller’s Index action. You can also navigate to the live site directly from the administration interface by opening the application list and clicking the Live site button at the bottom of the list.
Alternatively, you can switch to the Edit mode and use the Page tab, enabled for pages of the Home type, to preview the page’s content. Since we have also enabled the page builder and included the necessary scripts and methods required for its functionality in the corresponding view, you can see the added editable area rendered at the bottom of the page.
Developing the Medical center page
Creating the Medical center view model
In Visual Studio, create a new MedicalCenter subfolder in the Models folder.
Select the MedicalCenter subfolder and add a new MedicalCenterViewModel class.
Define the view model properties and their mappings using the following code:
using CMS.DocumentEngine.Types.MEDIO; namespace MEDIOClinic.Models { public class MedicalCenterViewModel { // Defines the properties of the MedicalCenter view model public string DocumentName { get; } public string MedicalCenterHeader { get; } public string MedicalCenterText { get; } // Maps the data from the MedicalCenter page type's fields to the view model properties public MedicalCenterViewModel(MedicalCenter medicalCenterPage) { DocumentName = medicalCenterPage.DocumentName; MedicalCenterHeader = medicalCenterPage.Fields.Header; MedicalCenterText = medicalCenterPage.Fields.Text; } } }
Save your changes.
Creating the Medical center controller
In the Controllers folder, create a new MedicalCenterController class.
Replace the default controller code with the following:
using System.Web.Mvc; using CMS.DocumentEngine.Types.MEDIO; using CMS.SiteProvider; using MEDIOClinic.Models; namespace MEDIOClinic.Controllers { public class MedicalCenterController : Controller { // GET: Loads and displays the site's Medical center page public ActionResult Index() { // Retrieves the Medical center page using the 'GetMedicalCenter' method from the page type's generated provider MedicalCenter medicalCenterNode = MedicalCenterProvider.GetMedicalCenter("/Medical-Center", "en-us", SiteContext.CurrentSiteName) .Columns("DocumentName", "MedicalCenterHeader", "MedicalCenterText"); // Creates a new MedicalCenterViewModel instance based on the page data var medicalCenterModel = new MedicalCenterViewModel(medicalCenterNode); return View(medicalCenterModel); } } }
Save your changes.
Creating the Medical center view
To define the output code of the Medical center page, create a view that uses MedicalCenterViewModel as its model class. The page type contains a field that is managed by a rich text editor, which means you need to handle potential HTML elements in the content (for example text styling, hyperlinks, images, etc.).
To display the content of the rich text editor fields in MVC views, use either the Html.Kentico().ResolveUrls extension method or the standard Html.Raw method. Both methods disable HTML encoding for the submitted value.
The ResolveUrls method additionally resolves relative URLs to their absolute form. The system already automatically resolves relative URLs by processing the output of all pages. But we still recommend calling the ResolveUrls method for rich text fields to minimize the output filtering requirements.
Right-click the Index() action in the MedicalCenterController class and select Add View.
Set the new view’s properties as follows:
- View name: Index
- Template: Empty
- Model class: MedicalCenterViewModel (MEDIOClinic.Models)
In the view code, set the ViewBag.Title value to the model’s DocumentName property:
@{ ViewBag.Title = Model.DocumentName; }
From the medical-center.html file in the tutorial resources, copy the HTML code of the two <section> elements in the body tag (styled with the teaser and content CSS classes) to the MedicalCenter view.
In the teaser section, replace the text of the paragraph tag with the Model.MedicalCenterHeader property.
In the content section, replace both the heading and the paragraph with the following Razor call:
@Html.Kentico().ResolveUrls(Model.MedicalCenterText)
Save your changes.
The final code of your MedicalCenter view should look like this:
@model MEDIOClinic.Models.MedicalCenterViewModel
@{
ViewBag.Title = Model.DocumentName;
}
<section class="teaser">
<div class="col-sm-offset-3 col-sm-4">
<p>@Model.MedicalCenterHeader</p>
</div>
<div class="clearfix"></div>
</section>
<section class="content">
<div class="col-sm-offset-3 col-sm-5">
@Html.Kentico().ResolveUrls(Model.MedicalCenterText)
</div>
<div class="clearfix"></div>
</section>
Previewing the Medical center page
You can preview your page in the Pages application in the Kentico administration interface or click the Live site button to view the page in the browser. Like with the Home page, the default route mapped in the project’s RouteConfig ensures that the http://localhost/Kentico12_MEDIOClinic/MedicalCenter URL targets the corresponding controller and its default Index action.
You have now built components in your MVC application that retrieve and present the content of the site’s pages. Let’s continue by building the website’s navigation in the last step of the tutorial!
Previous page: Creating the website layout — Next page: Creating the navigation menu
Completed pages: 8 of 10