adoconnection / RazorEngineCore

.NET6 Razor Template Engine
MIT License
565 stars 84 forks source link

How to use ViewBag #105

Closed SpringHgui closed 2 years ago

SpringHgui commented 2 years ago

How to use ViewBag

adoconnection commented 2 years ago

Hi, you need to make custom razor engine template class and inhert RazorEngineTemplateBase then you can put any custom members in this new template class

like this https://github.com/adoconnection/RazorEngineCore/wiki/Strongly-typed-model

SpringHgui commented 2 years ago

my Template

    public class CustomTemplateBase : RazorEngineTemplateBase
    {
        public dynamic ViewBag { get; set; }
    }

use


  return template.Run(instance =>
  {
      instance.ViewBag =  new
                {
                    title = "hello"
                },
      instance.Model = model;
  });

 // cshtml

  <h1>@ViewBag.title</h1>

get exception

'object' does not contain a definition for 'title'

adoconnection commented 2 years ago

Hi, everything is fine, but although ViewBag is dynamic it does not give you permission to access anonymous object proeprties.

RazorEngine engineCore = new RazorEngine();

var compiledTemplate = engineCore.Compile<CustomTemplateBase>("<h1>@ViewBag.title</h1>");

Console.WriteLine(compiledTemplate.Run(instance =>
{
    instance.ViewBag = new AnonymousTypeWrapper(new 
    {
        title = "hello"
    });
}));
SpringHgui commented 2 years ago

worked