In this tutorial, you will learn how to create and publish a page using code with Umbraco CMS. Most pages within your Umbraco website will be created by a content editor.  This is fine for ad-hoc pages, but, let's say you're in the middle of a content migrations from an old CMS and you have thousands of pages to migrate, or you need to frequently import data from a third-party, manually creating pages might not be the most efficient route.

How To Save A PAge In Code

Creating a page programmatically in Umbraco is quite straightforward.  You will need to use the 'ApplicationContext' API, like so:

The code above will work but it has a flaw.. like line specifically, content.SetValue("propertyName", someData).  In this line I'm hardcoding a property name within code...  if someone renamed this property within the Umbraco editor, my code would break.  What is worse, I'd have no clue about it!!!

If you are new to Umbraco and you have yet to learn about strongly-typed models and code first, I suggest you read this.  I've talked for years about the benefits of defining your document-types in code.  If you don't use strongly-typed models there is a strong possibility that one day your code will break as a content editor has updated a property within Umbraco and now all your hard-coded property names will break.  To fix this, I strongly suggest you write your Umbraco code to the models the Umbraco Model builder generates.  Using the example about, this would look like this, assuming we have a strongly-typed model called LandingPage:

New Way

This second way of using reflection using the classes/models Umbraco generates rather than hard-coding them yourself will make your code-base a lot more robust.  It will make unit testing and finding bugs within your codebase a lot more simple and, basically, everyone at work will think you're some sort of genius rockstar, enjoy!