简体   繁体   中英

Can I use anonymous types as a Razor model?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM