Category Archives: Razor

Razor templates in your Xamarin application

I had a situation where I wanted to have a template file made up of HTML along with data supplied by my Xamarin application. There are several options to do this but a Razor template file would be a perfect fit, but how to embed one in my (non-Web) application?

Note: Whilst this post talks about a Xamarin application this should be usable in other types of application.

  • I created a Templates folder (not required for this to work) in my solution.
  • Within the Templates folder I add a new text file but saved with a .cshtml extension, for example EmployeeTemplate.cshtml. Visual Studio 2019 doesn’t have a specific template for Xamarin application, but just naming it with the correct extension works.
  • Select the file in the solution explorer and open it’s properties, set the Custom Tool to RazorTemplatePreprocessor.

Here’s a snippet of the contents within the Razor template file

<div class="row">
  <div>Date: @Model.DateEntered</div>
    <div>
      <div>Employee Number:</div>
      <div>@Model.OrderDetails.EmployeeNumber</div>
    </div>
</div>

Visual Studio will (due the use of the RazorTemplatePreprocessor Custom Tool) generate a .cs file that is a class that we can pass our model into and will process the template file and output a string representing the combination of the template with our model.

To generate our output string we simply use the following code

var template = new EmployeeTemplate() 
{ 
  Model = viewModel 
};

var result = template.GenerateString();