0

I have a C# server where I manually render some Razor views using the RazorEngine NuGet library. The model supplied to the view is an anonymous type, created as follows:

new[] { Foo = "Bar", Baz = "Example" }

Because of the way I'm rendering my template, Visual Studio isn't aware of my model. This means that Visual Studio considers code like this invalid, even though it works fine:

<p>@Model.Foo</p>

To rectify this, I have discovered the @model directive, but this appears only to work with classes as the specified model. For example, these are both considered invalid:

@model { string Foo, string Baz }
@model (string Foo, string Baz)

Is there any way I can get @model to work with anonymous types? Alternatively, named tuples would satisfy the compiler too, since I never update any of my model's fields from the template.

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78

1 Answers1

0

Yes you can, but I wouldn't normally as strongly typed view models have their advantages.

Create your model like this:

dynamic model = new ExpandoObject();
model.Foo = "Bar";
model.Baz = "Example";

And then you can access it in the view, no problem

<h1>@Model.Foo</h1>
<h2>@Model.Baz</h2>

NB. By default a RazorPage<T> is defined as RazorPage<dynamic>, so there's no need to declare @model dynamic.

James Law
  • 6,067
  • 4
  • 36
  • 49
  • There's no problem with the *function* of my templates; the problem is that Visual Studio thinks there's a problem when in fact there is not, because the IDE is not aware of my model. Also, using an `ExpandoObject` as the model parameter of `RazorEngine.Engine.Razor.RunCompile` does not compile. Thanks for replying though. – Aaron Christiansen Nov 22 '17 at 18:11