In this tutorial, you will learn how to create and publish a page using Umbraco CMS, all through the power of code!!!! 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 need to perform a content migration. You have an old CMS which contains thousands of pages. You need to migrate them to your new website. Manually copying content might take weeks of effort. Writing some code to import the content automatically can be a lot more efficient! Another example where creating content via code is handy is around importing data from a third party. In these situations, 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, however, it has a flaw. In Line11
content.SetValue("propertyName", someData). 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 high risk that one day your code will break. If a content editor renamed the property within the backend all the code that contained hard-coded property references will not work. To avoid these situations, I suggest you write your Umbraco access layer code using models generated by the Umbraco Model builder. Using the example above, this would look like this:
Using reflection via models generated with the model's builder to save properties will make your code-base a lot more robust. It will make unit testing and finding bugs within your codebase a lot more simple. Basically, everyone at work will think you're some sort of genius rockstar 🎤🎤🎤
You now have an easy way to create content programmatically in code. Happy Coding 🤘