有没有办法在剃刀视图中解析DTO上的嵌套接口? [英] Is there a way to resolve nested interfaces on DTOs in a razor view?

查看:53
本文介绍了有没有办法在剃刀视图中解析DTO上的嵌套接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们遇到了Razor视图引擎无法解决嵌套接口的问题.示例代码:

We are having an issue with the Razor view engine not resolving nested interfaces. Sample code:

public interface IDto
{
    Guid Id {get;set;}
}

public interface IUserDto: IDto
{
  string Username {get;set;}
}

//The view
@model IUserDto

//pukes on this line
@Html.DisplayFor(u => u.Id)

我们应该在视图上使用具体模型吗?Razor视图引擎是否无法为每个模型使用多个接口?

Should we be using concrete models on our views? Is the Razor view engine not capable of using multiple interfaces per model?

推荐答案

这是ASP.NET MVC 3中的一项更改,

This was a change in ASP.NET MVC 3 that I already brought to the attention of Microsoft (this scenario worked on ASP.NET MVC 1 and 2).

这是他们的官方答案:

达林(及其他),

Hi Darin (and others),

这是我们对ASP.NET MVC 3引入的蓄意更改,是在获得更好的支持之间进行权衡的结果继承的模型或对实现的模型的更好支持接口.我们最终赞成继承的模型,这是从我们的经验是一种更常见的方法.

This was a deliberate change that we introduced to ASP.NET MVC 3 that was the result of a trade-off between having better support for inherited models or better support for models that implement interfaces. We ended up favoring inherited models, which from our experience is a more common approach.

基本问题是,当接口由该类不真正 继承该类的任何成员的类接口.这里的关键是因为它不继承接口的成员,它也不会继承元数据这些成员.

The fundamental problem is that when an interface is implemented by a class that the class doesn't really inherit any of the members of the interface. The key here is that because it doesn't inherit the members of the interface, it also does not inherit the metadata on those members.

谢谢,ASP.NET团队

Thanks, The ASP.NET Team

现在到了重点

我们应该在视图上使用具体模型吗?

Should we be using concrete models on our views?

不是必需的.您仍然可以在主视图上使用界面,但是可以使用具有具体类型的编辑器/显示模板.在运行时,框架将根据视图模型的实际类型选择正确的模板,在其中您将拥有具体的类型,并且它将解析Id属性.

Not necessary. You could still use interfaces on your main views, but then have editor/display templates with concrete types. At runtime based on the actual type of the view model the framework will pick the correct template where you will have the concrete type and it will resolve the Id property.

另一种可能性是使用抽象类而不是接口(我知道,Berkk通常是微软语言的)

Another possibility is to use abstract classes instead of interfaces (beurk I know :-) typically Microsoftish)

这篇关于有没有办法在剃刀视图中解析DTO上的嵌套接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆