Search code examples
c#asp.netasp.net-corerazorrazor-pages

How to get key list from razor engine template in c#?


I am working with .net core.
Project contains many dynamic razor engine templates. All the templates are generated by the third-party users. So the system can not use any common model or can not generate the individual model for fill razor engine template with values.
I need to get list of all the keys which are using in razor engine template.

<acord>
  <student>
     <firstName>@Model.StudentFirstName</firstName>
     <lastName>@Model.StudentLastName</lastName>
     @if(@Model.StudentPhone != null)
     {
        <phone>@Model.StudentPhone</phone>
     }
  </student>
  <parents>
     <firstName>@Model.parentFirstName</firstName>
     <lastName>@Model.parentLastName</lastName>
  </parents>
</acord>

As per above sample, I need list of keys like,
@Model.StudentFirstName, @Model.StudentLastName, @Model.StudentPhone, @Model.parentFirstName @Model.parentLastName

I have spent couple of days for find the solution on internet, but didn't get any proper solution. So how can I get list of keys from razor engine template?


Solution

  • You could use regular expressions. Based on the example you posted, the following works:

    var input = @"<acord>
      <student>
         <firstName>@Model.StudentFirstName</firstName>
         <lastName>@Model.StudentLastName</lastName>
         @if(@Model.StudentPhone != null)
         {
            <phone>@Model.StudentPhone</phone>
         }
      </student>
      <parents>
         <firstName>@Model.parentFirstName</firstName>
         <lastName>@Model.parentLastName</lastName>
      </parents>
    </acord>";
    var pattern = @"@Model.([\w.\[\]]*)";
    var keys = Regex.Matches(input, pattern)
        .Cast<Match>()
        .Select(m => m.Groups.Cast<Group>().LastOrDefault())
            .Select(g => g.Value)
            .Distinct()        
            .ToList();
    foreach(var k in keys)
    {
        Console.WriteLine(k);
    }
    

    Output:

    StudentFirstName
    StudentLastName
    StudentPhone
    parentFirstName
    parentLastName