How do I get the name, set in the CMS, of a certain block in an MVC view?
I guess that it should be @Model.Name
but I can't find it.
How do I get the name, set in the CMS, of a certain block in an MVC view?
I guess that it should be @Model.Name
but I can't find it.
You have to cast your block instance to IContent
to access the Name
property.
For details on why, you can have a look at: Episerver - Why BlockData doesn't implement IContent
The syntax to get the Name property is
(Model as IContent).Name
or
((IContent)Model).Name
Be careful with this cast as handling a Block which is a property as opposed to a ContentReference will not work and throws an exception.
var blockName = (Model as IContent)?.Name ?? "Local block"
to avoid a potential null reference exception. To use the null-coalescing operator in a Razor view you need to enable C# 6+ with the Microsoft.CodeDom.Providers.DotNetCompilerPlatform
NuGet package, though. –
Relentless Name
property, so that it's accessible without the extra hassle. :) –
Relentless Name
without tying the object to IContent
, which is what they were trying to avoid. I'm considering an extension method for a base block type to return the block as IContent
since I seem to be writing this bit of code quite a lot! –
Moitoso If you want to display the name in the view - you can cast the model inside PropertyFor: @Html.PropertyFor(m => ((IContent)m).Name)
© 2022 - 2024 — McMap. All rights reserved.