ps-team
10/27/2017 - 9:48 AM

Smarter variable assignment of Meta Data to prevent Razorviews from potentially falling over

Smarter variable assignment of Meta Data to prevent Razorviews from potentially falling over

@using Contensis.Framework.Web

@{

  @*
    - Sometimes meta data does not always become instantly available when building/previewing templates/pages, 
    - or if the preview database is cleared and is in the process of rebuilding itself.
    - 
    - Depending on how you access the meta data, this can cause a razorview to fall over:
    - ERROR: 'Cannot perform runtime binding on a null reference'
    - 
    - By using a ternary (conditional) if statement, we can safely assign meta data variables and capture ones 
    - that are not yet available using 1 line of code
  *@
    
    
    
  /*
   * EXAMPLE 1 - WILL ERROR
   *
   * This simple assignment will cause a razorview to fall over with the above error 
   * if the description meta data is not available.
   */
  string description = CurrentNode.Data.MD_description.ToString();
  
  <p>@description</p>
  
  
  
  /*
   * EXAMPLE 2 - WILL NOT ERROR
   *
   * Using a ternary if statement we can assign a variable to the value of the meta data if 
   * available, or assign it as a empty string if not available.
   * 
   * We can then wrap the html output in a if statement that checks for null/empty values
   * so we don't get empty html tags being rendered back to the page.
   */
  string description = CurrentNode.Data.MD_description != null ? CurrentNode.Data.MD_description.ToString() : string.Empty;
  
  if(!string.IsNullOrEmpty(description))
  {
      <p>@description</p>
  }
  
}