简体   繁体   English

我可以使用匿名类型作为Razor模型吗?

[英]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. 我有一台C#服务器,在其中使用RazorEngine NuGet库手动呈现一些Razor视图。 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. 由于我呈现模板的方式,Visual Studio无法识别我的模型。 This means that Visual Studio considers code like this invalid, even though it works fine: 这意味着即使它可以正常工作,Visual Studio仍认为这样的代码无效:

<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. 为了纠正这一点,我发现了@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? 有什么办法可以让@model使用匿名类型? 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 . 默认情况下, RazorPage<T>被定义为RazorPage<dynamic> ,因此无需声明@model dynamic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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