ASP.NET MVC add HiddenInput attribute to Model in

2019-07-17 19:22发布

问题:

I'm working on an asp.net MVC 3 application which is using Data Models from a compiled library. However I would like to be able to add the following declaration to some data model properties in the compiled dll:

[HiddenInput(DisplayValue = false)]

The problem is that I don't have the source for the DLL and the author doesn't want to introduce a dependency on System.Web.Mvc. Is there a way, using partial classes or something like that, that would allow me add this attribute?

Mark

回答1:

No, there is no way. Attributes are baked in the metadata of the assembly at compile time and existing classes cannot be modified at runtime. As far as partial classes are concerned they only work within the same assembly.

Also if the authors of this assembly don't want to introduce a dependency in their library with System.Web.Mvc they probably have reasons for this. Obviously, you, as an MVC developer should use view models which are classes specifically tailored to the needs of your views and then map between the domain models (stuff that comes from different libraries, ...) and view models. Then you would pass those view models to the view and not the domain models. Of course your view models will have all the necessary metadata and formatting such as DisplayName, Hidden, ... To ease the mapping between those two classes you could use AutoMapper.



回答2:

You could map your compiled library Data Models to a set of local models.

If you were to map your compiled library Data Models to your own set of local models you could do what you like.

You can do this manually or look at a tool like AutoMapper.



回答3:

Add reference to system.web.mvc to your class project.