Creating content
The most important component you will be using when creating content in Umbraco is the ContentService. It's one of the many services in Umbraco and it is available directly from the surface controller that you built in the previous video.
The Content Service is your gateway to the Content API which you'll need to interact with in order to create, save and publish content to your Umbraco website.
These Umbraco Services can also be accessed from other places, other Umbraco Controllers, like API Controllers and regular MVC controllers.
If you want to learn more about what services are available and what they are most commonly used for, you can find links to the Umbraco Documentation in the "Resources" section below.
Create() method
To create content programmatically with Umbraco, you need to use the Create() method which is available in the Content Service.
The method takes three parameters:
Two ways to place the new content node in the content tree
To place the new piece of content in the content tree, you need to define a "parent ID".
In the video, the parent ID is set by using the GUID of an already existing page on the website. This is considered "hard-coding", meaning that it will at all times be that content item that will act as parent.
The parent ID can also be set dynamically. This can be done by using a series of methods to look through the content tree for the first instance using a given Document Type.
Below is a sample of how the parent ID could be defined dynamically:
// Get the first item matching the "Articles" Document Type
var parentNode = ContentAtRoot().FirstOrDefault.ChildrenOfType<Articles>().FirstOrDefault();
// Create a new variable for the parent ID
var parentId = parentNode.Key;
Persisting changes
Creating the content node is the first step in creating new content on the website. The second step is to also use the data from the form-submission to populate the properties on the selected Document Type.
This is done by persisting the changes using the SetValue() method. With this method, we take the value from the mode - from the data submitted via the form and map it to the property on the Document Type on the newly created piece of content.
Once that has been done for all the data and the corresponding properties in the Document Type used for the content, you can save and, if you want, also publish the content item, and it will automatically be public and live on your website.
Resources
Check out the resources below to learn more about MVC and MVC in Umbraco.
Project login details
User: tv@umbraco.com
Password: 1234567890
In the Surface Controllers chapter, you will learn more about some of the key functionality in Umbraco and how you can use MVC to programmatically add content and media to your Umbraco website.