1

在使用 Asp.Net MVC 一段时间后,我决定在项目中实际使用它。出现的问题之一是前端站点对于给定模型的验证规则可能与管理面板不同。

我知道 MetadataType 属性,但由于您有多个上下文,这对我们来说是开箱即用的。

为了解决这个问题,我实现了一个自定义 ModelMetadataProvider,它根据请求的执行上下文将默认的 ModelMetdataProvider 重定向到不同的类型。这对于显示所需的 UI 非常有效。

我不喜欢这个解决方案的部分是我最终从我的自定义模型元数据提供程序中读取堆栈,以确定给定的调用是否用于模型绑定。这是因为当我没有这样做时,我会在从控制器调用 TryUpdateModel 期间正确地得到“对象与目标类型不匹配”,因为模型绑定器试图使用类型 A 的属性来将值设置为类型 B 的实例.

阅读调用堆栈对生产来说是个坏主意吗?有没有办法在不使用属性的情况下选择性地复制 MetadataTypeAttribute 行为?

提前致谢,

约翰

4

2 回答 2

0

This is one of those instances where you wish the ASP.NET MVC Team hadn't sealed a class - I'm sure they had their reasons. I was going to suggest simply creating your own attribute, derived from MetadataTypeAttribute.

One way to go about this is to take the source of the attribute and write your own:

http://dotnetinside.com/framework/v4.0.30319/framework/v4.0.30319/System.ComponentModel.DataAnnotations/MetadataTypeAttribute

Although, of course, this makes your code less maintainable.

I would assert that to the best of my knowledge, you are already making the right decision with a ModelMetadataProvider as your solution. I'm a little nervous for you regarding analysing the call stack though, change locations, move something to an area; you get my drift, i.e. it would be very easy to break the code with a build time decision that isn't found until runtime or beyond QA.

You haven't supplied how the context is roughly determined, but I would personally tackle that by adding a property to the class itself with an Enum (finite possibilities and design time breakage) with a list of possible contexts, then during spin up of the class, populate it, ready for execution of the Provider, which will pass through the correct metatdatatype based on the value of the Enum.

Many ways to skin this cat, but something that is going to break on build will serve you best, IMHO.

于 2013-08-05T19:25:24.553 回答
0

除非您使用 MVC 6,否则您可能会发现ModelMetadata Fluent Configuration很有用。

可以在此处此处找到有关如何使用它的一些很好的示例。

真正重要的是,它只是完全在您控制之下的代码。因此,一旦你有不同的上下文,你可能会决定定义不同的配置,或者你可能会更加努力并为不同的上下文制作(一组)不同的注册

真正有帮助的是基类的“装饰”(故意使用的术语!)属性,至少似乎没有什么能阻止你这样做。

编辑:模型元数据不应WCF RIA Services Contrib混淆。

于 2016-03-18T10:00:07.190 回答