Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 989
Mike Koder Avatar asked Mar 12 '13 11:03

Mike Koder


1 Answers

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);
     }
like image 196
Dave Jellison Avatar answered Nov 15 '22 11:11

Dave Jellison