根据另一个属性在视图中显示模型属性的最佳实践

时间:2022-03-29 13:23:59

I am creating an MVC 4 application in ASP.NET 4.0. In my View I am displaying the Properties of a Model; one Property in particular may need to be hyperlink with a tooltip depending on another Property in the Model.

我在ASP.NET 4.0中创建一个MVC 4应用程序。在我的视图中,我正在显示模型的属性;特别是一个属性可能需要是带有工具提示的超链接,具体取决于模型中的另一个属性。

It's easier to explain by showing the code in the View:

通过在视图中显示代码更容易解​​释:

@if (Model.HasMultipleErrorReasons)
{
   <td data-toggle="tooltip" title="@Model.AllErrors"><a href="#">Multiple</a></td>
}
else
{
   <td>@Model.Error</td>
}

I know there is nothing wrong with this and that it is functional, but I would prefer to not have to write out the <td></td> twice; the example above is very stripped down and in practice it is much messier.

我知道这没有任何问题,并且它是有用的,但我宁愿不必写出 两次;上面的例子非常简单,实际上它更加混乱。

Is there a way to avoid this or a better way to do it?

有没有办法避免这种或更好的方法呢?

1 个解决方案

#1


0  

That's kind of the breaks of the game when working with templated rendering engines. You could abstract the code in some way so you don't have to see it, either using a partial view or a HtmlHelper extension. However, there's slight but not insignificant performance cost to using partial views, so if you end up with a ton of different partial views being rendered on the same page for multiple things like this, you'll feel it. This is also probably overkill for an extension. Although, if you can boil the code down enough that it would be applicable to a wide range of uses, it might warrant creating an extension method.

当使用模板化渲染引擎时,这就是游戏的中断。您可以以某种方式抽象代码,这样您就不必使用局部视图或HtmlHelper扩展来查看它。但是,使用部分视图会有轻微但不显着的性能成本,因此如果你最终会在同一页面上呈现大量不同的部分视图来处理这样的多个事情,那么你会感觉到它。对于扩展来说,这也可能有点过分。虽然,如果您可以将代码简化到足以使其适用于广泛的用途,则可能需要创建扩展方法。

Overall, I would say just keep it as you have it.

总的来说,我会说保持它,就像你拥有它。

#1


0  

That's kind of the breaks of the game when working with templated rendering engines. You could abstract the code in some way so you don't have to see it, either using a partial view or a HtmlHelper extension. However, there's slight but not insignificant performance cost to using partial views, so if you end up with a ton of different partial views being rendered on the same page for multiple things like this, you'll feel it. This is also probably overkill for an extension. Although, if you can boil the code down enough that it would be applicable to a wide range of uses, it might warrant creating an extension method.

当使用模板化渲染引擎时,这就是游戏的中断。您可以以某种方式抽象代码,这样您就不必使用局部视图或HtmlHelper扩展来查看它。但是,使用部分视图会有轻微但不显着的性能成本,因此如果你最终会在同一页面上呈现大量不同的部分视图来处理这样的多个事情,那么你会感觉到它。对于扩展来说,这也可能有点过分。虽然,如果您可以将代码简化到足以使其适用于广泛的用途,则可能需要创建扩展方法。

Overall, I would say just keep it as you have it.

总的来说,我会说保持它,就像你拥有它。