ASP.NET MVC 3 HtmlHelper Exception does not recognize ModelMetadata on inherited interface

梦想的初衷 提交于 2019-11-28 18:23:09

There has been a breaking change/bug in ASP.NET MVC 3 in the System.Web.Mvc.ModelMetadata. FromLambdaExpression method which explains the exception you are getting:

ASP.NET MVC 2.0:

...
case ExpressionType.MemberAccess:
{
    MemberExpression body = (MemberExpression) expression.Body;
    propertyName = (body.Member is PropertyInfo) ? body.Member.Name : null;
    containerType = body.Member.DeclaringType;
    flag = true;
    break;
}
...

ASP.NET MVC 3.0

...
case ExpressionType.MemberAccess:
{
    MemberExpression body = (MemberExpression) expression.Body;
    propertyName = (body.Member is PropertyInfo) ? body.Member.Name : null;
    containerType = body.Expression.Type;
    flag = true;
    break;
}
...

Notice how the containerType variable is assigned a different value. So in your case in ASP.NET MVC 2.0 it was assigned the value of IOwned which is the correct declaring type of the AuthorId property whereas in ASP.NET MVC 3.0 it is assigned to IActivity and later when the framework tries to find the property it crashes.

That's the cause. As far as the resolution is concerned I would wait for some official statement from Microsoft. I can't find any relevant information about this in the Release Notes document. Is it a bug or some feature which needs to be workarounded here?

For now you could either use the non-strongly typed Html.Hidden("AuthorId") helper or specify IOwned as type for your control (I know both suck).

From the MVC team:

Unfortunately, the code was actually exploiting a bug that was fixed, where the container of an expression for ModelMetadata purposes was inadvertently set to the declaring type instead of the containing type. This bug had to be fixed because of the needs of virtual properties and validation/model metadata.

Having interface-based models is not something we encourage (nor, given the limitations imposed by the bug fix, can realistically support). Switching to abstract base classes would fix the issue.

With thanks to Burcephal, whos answer pointed me in the right direction

You can create a MetaDataProvider which will get around this issue, the code here adds to the code in the base class checking for the property on implemented interfaces of a model which is itself an interface.

public class MyMetadataProvider
    : EmptyModelMetadataProvider {

    public override ModelMetadata GetMetadataForProperty(
        Func<object> modelAccessor, Type containerType, string propertyName) {

        if (containerType == null) {
            throw new ArgumentNullException("containerType");
        }
        if (String.IsNullOrEmpty(propertyName)) {
            throw new ArgumentException(
                "The property &apos;{0}&apos; cannot be null or empty", "propertyName");
        }

        var property = GetTypeDescriptor(containerType)
            .GetProperties().Find(propertyName, true);
        if (property == null
            && containerType.IsInterface) {
            property = (from t in containerType.GetInterfaces()
                        let p = GetTypeDescriptor(t).GetProperties()
                            .Find(propertyName, true)
                        where p != null
                        select p
                        ).FirstOrDefault();
        }

        if (property == null) {
            throw new ArgumentException(
                String.Format(
                    CultureInfo.CurrentCulture,
                    "The property {0}.{1} could not be found",
                    containerType.FullName, propertyName));
        }

        return GetMetadataForProperty(modelAccessor, containerType, property);
    }
}

and as above, set your provider the global.asax Application_Start

ModelMetadataProviders.Current = new MyMetaDataProvider();

f you are interrested, I have implemented a little work around for it in my app. As I was going through the MVC source code, I found that the FromLambdaExpression method named below will be calling the MetaDataProvider which is an overridable singleton. So we could just implement that class that will actually try the inhereted intefaces if the first one does not work. It will also go up the tree of intefaces.

public class MyMetaDataProvider : EmptyModelMetadataProvider
{
    public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
    {
        try
        {
            return base.GetMetadataForProperty(modelAccessor, containerType, propertyName);
        }
         catch(Exception ex)
        {
            //Try to go up to type tree
            var types = containerType.GetInterfaces();              
            foreach (var container in types)
            {
                if (container.GetProperty(propertyName) != null)
                {
                    try
                    {
                        return GetMetadataForProperty(modelAccessor, container, propertyName);
                    }
                    catch
                    {
                        //This interface did not work
                    }
                }
            }               
            //If nothing works, then throw the exception
            throw ex;
        }              
    }
}

and then, just cange the implementation of the MetaDataProvider in the global.asax Application_Start()

ModelMetadataProviders.Current = new MyMetaDataProvider();

It is not the best code ever, but it does the job.

Try using typecast. It works for my project although resharper highlights it as redundant.

For your code the solution would be

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IActivity>" %>
<%: Html.HiddenFor(item => ((IOwned)item).AuthorId) %>

Furthering Anthony Johnston's answer, you might find that you get exceptions when using DataAnnotations, as the AssociatedValidatorProvider.GetValidatorsForProperty() method will try to use the inheriting interface as the container type rather than the base one and therefore fail to find the property again.

This is the reflected code from the GetValidatorsForProperty method (it is the second line which causes the propertyDescriptor variable to be null and thus the exception to be thrown) :

private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, ControllerContext context)
{
    ICustomTypeDescriptor typeDescriptor = this.GetTypeDescriptor(metadata.ContainerType);
    PropertyDescriptor propertyDescriptor = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);
    if (propertyDescriptor != null)
    {
        return this.GetValidators(metadata, context, propertyDescriptor.Attributes.OfType<Attribute>());
    }
    else
    {
        object[] fullName = new object[] { metadata.ContainerType.FullName, metadata.PropertyName };
        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, MvcResources.Common_PropertyNotFound, fullName), "metadata");
    }
}

If so, I believe that the following code may help, as it makes sure that the ContainerType is set to the type which the property is on, not the type of the view model.

Disclaimer: It seems to work fine, but I have not fully tested it yet so it might have undesired effects! I also understand it is not written perfectly, but I was trying to keep the format similar to the previous answer for ease of comparison. :)

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
    public override ModelMetadata GetMetadataForProperty(
        Func<object> modelAccessor, Type containerType, string propertyName)
    {

        if (containerType == null)
        {
            throw new ArgumentNullException("containerType");
        }
        if (String.IsNullOrEmpty(propertyName))
        {
            throw new ArgumentException(
                "The property &apos;{0}&apos; cannot be null or empty", "propertyName");
        }

        var containerTypeToUse = containerType;

        var property = GetTypeDescriptor(containerType)
            .GetProperties().Find(propertyName, true);
        if (property == null
            && containerType.IsInterface)
        {

            var foundProperty = (from t in containerType.GetInterfaces()
                        let p = GetTypeDescriptor(t).GetProperties()
                            .Find(propertyName, true)
                        where p != null
                        select (new Tuple<System.ComponentModel.PropertyDescriptor, Type>(p, t))
                        ).FirstOrDefault();

            if (foundProperty != null)
            {
                property = foundProperty.Item1;
                containerTypeToUse = foundProperty.Item2;
            }
        }


        if (property == null)
        {
            throw new ArgumentException(
                String.Format(
                    CultureInfo.CurrentCulture,
                    "The property {0}.{1} could not be found",
                    containerType.FullName, propertyName));
        }

        return GetMetadataForProperty(modelAccessor, containerTypeToUse, property);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!