ASP.NET MVC Editor-Templates/UIHint with parameters
You could use the AdditionalMetadata
attribute:
[UIHint("DateTime")]
[AdditionalMetadata("foo", "bar")]
public DateTime Date { get; set; }
and in the template:
@ViewData.ModelMetadata.AdditionalValues["foo"]
so if you wanted to pass an url:
[UIHint("DateTime")]
[AdditionalMetadata("controller", "somecontroller")]
[AdditionalMetadata("action", "someaction")]
[AdditionalMetadata("property", "someproperty")]
public DateTime Date { get; set; }
and in your template:
@{
var values = ViewData.ModelMetadata.AdditionalValues;
}
<script type="text/javascript">
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action((string)values["action"], (string)values["controller"])',
dataType: "json",
data: {
filter: request.term
},
success: function (data) {
response(
$.map(eval(data), function (item) {
return {
label: item['@values["property"]']
}
})
);
}
});
}
});
</script>
You could use the UHint without AdditionalMetadata attribute, but some additional code is requred
[UIHint("DateTime", null, "key1", "value1", "key2", "value2")]
public DateTime Date { get; set; }
override CreateMetadata:
public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
public const string UiHintControlParameters = "UiHintControlParameters";
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
ModelMetadata metadata = base.CreateMetadata(
attributes,
containerType,
modelAccessor,
modelType,
propertyName);
IEnumerable<UIHintAttribute> uiHintAttributes = attributes.OfType<UIHintAttribute>();
UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => string.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));
if (uiHintAttribute != null)
{
metadata.AdditionalValues.Add(UiHintControlParameters, uiHintAttribute.ControlParameters);
}
return metadata;
}
Register CustomMetadataProvider:
public static void Application_Start()
{
ModelMetadataProviders.Current = new CustomMetadataProvider();
}
and in your template:
@{
IDictionary<string, object> values = (IDictionary<string, object>)
ViewData.ModelMetadata.AdditionalValues[CustomMetadataProvider.UiHintControlParameters];
}