Skip to main content

MVC views

Within an MVC view, you may have conditional logic that controls what markup the view exposes. A common example is a view that includes third-party trackers only if the visitor has accepted a privacy policy.

With traditional Sitecore, this logic might be hard-coded into the view using C# code. That C# code will not run when Uniform is used to decouple delivery from the Sitecore CD instance.

Uniform provides a way to create conditional blocks that are compatible with the supported personalization engines (e.g. edge-based personalization engine) without you having to write code that targets a specific personalization engine.

Example#

The example in this section demonstrates how to programmatically change the markup exposed by a view depending on which rule matches the visitor's context. Imagine a case where you want to display a pricing discount based on the business relationship the visitor has with your brand ("customer type"):

  • Wholesalers see 45% discount
  • Retailers see 10% discount
  • Premium retailers see 12% discount
  • Everyone else sees 5% discount

Define rules#

Rules are needed to define the conditions that determine the visitor's customer type. When a visitor logs into the site, a cookie is set that identifies the visitor's customer type:

  • If the cookie CT has a value of W, the visitor is a wholesaler.
  • If the cookie CT has a value of R, the visitor is a retailer.
  • If the cookie CT has a value of P, the visitor is a premium retailer.
  • If the cookie CT has any other value, or if the cookie doesn't exist, the visitor's customer type is unknown.
  1. In Sitecore, open Marketing Control Panel.
  2. Navigate to Personalization > Predefined Rules.
  3. Add a new item using the template Conditional Rendering Rule.
  4. Add a condition that checks if the cookie CT has a value of W.
  5. Note the item id. This is the id of the condition that determines the visitor is a wholesaler.
  6. Repeat these steps for the retailer and premium retailer customer types.

Add conditional blocks to view#

  1. Add the following code to your view:

    @Html.Uniform().RenderConditionalBlock(initialize =>{    const string WHOLESALER_CONDITION_ID = "";    const string RETAILER_CONDITION_ID = "";    const string PREMIUM_RETAILER_CONDITION_ID = "";    initialize.If(WHOLESALER_CONDITION_ID, @<div>45% discount</div>);    initialize.ElseIf(RETAILER_CONDITION_ID, @<div>10% discount</div>);    initialize.ElseIf(PREMIUM_RETAILER_CONDITION_ID, @<div>12% discount</div>);    initialize.Else(@<div>5% discount</div>);})
  2. For the constant WHOLESALER_CONDITION_ID, set the condition id from the previous section.

  3. For the constant RETAILER_CONDITION_ID, set the condition id from the previous section.

  4. For the constant PREMIUM_RETAILER_CONDITION_ID, set the condition id from the previous section.