Mike Koder
Mike Koder

Reputation: 1928

Add values to ModelMetadata.AdditionalValues when using EditorFor

If I have a convention to change the editor and set some values

public class MetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        var meta = base.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
        if (IsNumericType(propertyDescriptor.PropertyType))
        {
            meta.TemplateHint = "Number";

            var attr = propertyDescriptor.Attributes.OfType<RangeAttribute>().FirstOrDefault();
            if (attr != null)
            {
                meta.AdditionalValues["min"] = attr.Minimum;
                meta.AdditionalValues["max"] = attr.Maximum;
            }
        }
        return meta;
    }
    //...
}

Then I can get the additional values in the template

@{
    var min = ViewData.ModelMetadata.AdditionalValues["min"];
    var max = ViewData.ModelMetadata.AdditionalValues["max"];
}

However, if I use the same template like this

@Html.EditorFor(x => x.Number, new { min = 1, max = 10 })

Then I should get the values like this

@{
    var min = ViewData["min"];
    var max = ViewData["max"];
}

Can I somehow merge additionalViewData and ModelMetadata.AdditionalValues so that I could get the values from one place?

Upvotes: 6

Views: 2449

Answers (1)

Dave Jellison
Dave Jellison

Reputation: 933

I honestly haven't tried to see if the AdditionalValues get pulled properly but what does the built-in provide for you in your view?

    @using System.Web.Mvc

    @{
         var meta = ModelMetadata.FromLambdaExpression(model => model, ViewData);
     }

Upvotes: 1

Related Questions