Search code examples
episerver

Blocks in Episerver


So I am trying to create my first block. The idea of this block is to get latest news from an api end point and then show it on different pages on the website.

What I have understood is this

Create a block type, something like this

public class NewsBlock : BlockData
{

            [CultureSpecific]
            [Display(
                Name = "Heading",
                Description = "Add a heading.",
                GroupName = SystemTabNames.Content,
                Order = 1)]
            public virtual String Heading { get; set; }

}

Then I create a model for my Block

public class LatestNewsViewModel 
{
  public NewsBlock NewsBlock { get; private set; }
  public IEnumerable<dynamic> LatestNews { get; set; }

  public LatestNewsViewModel(NewsBlock latestNewsBlock, IEnumerable<dynamic> latestNews) 
  {
  NewsBlock = latestNewsBlock;
  LatestNews = latestNews;
}
}

Then I creata a block controller and in the index action I get data from my api and fill the block container data Then I create a partial view and then from controller pass data into the view Then from the dashboard I can add my block where ever I want on the site

Is this the way to do it? Or am I missing something?


Solution

  • That seem about correct. Please note there are many ways and opinions on how to get your data from the content model through the controller to the actual view. The example below is just the most simple scenario I can come up with.

    public class NewsBlock : BlockData
    {    
                [CultureSpecific]
                [Display(
                    Name = "Heading",
                    Description = "Add a heading.",
                    GroupName = SystemTabNames.Content,
                    Order = 1)]
                public virtual String Heading { get; set; }
    
    }
    

    The controller

    public class NewsBlockController : BlockController<NewsBlock>
    {
        // GET: NewsBlock
        public override ActionResult Index(NewsBlock currentBlock)
        {
            // apistuff
            ApiModelWhatever returnFromApi = "whatever";
    
            var model = new LatestNewsViewModel(currentBlock, returnFromApi);
            return PartialView(model);
        }
    }
    

    ViewModel

    public class LatestNewsViewModel 
    {
        public string Heading { get; private set; }
        public ApiModelWhatever ReturnFromApi { get; private set; }
    
        public LatestNewsViewModel(NewsBlock latestNewsBlock, ApiModelWhatever returnFromApi) 
        {
            Heading = latestNewsBlock.Heading;
            ReturnFromApi = returnFromApi;
        }
    }
    

    View

    @model LatestNewsViewModel
    
    <h2>@Html.PropertyFor(model => model.Heading)</h2>