Question

I'm trying to use my custom resource uploader template to upload a resource for my model but I can't find a way to get FileExtensions data annotation attribute metadata:

ViewModel:

public class ItemViewModel{
    [Required]
    public Name {get;set;}

    [Required]
    [Display(Name = "Resource"), FileExtensions(Extensions = ".res")]
    public UploadedResourceID{get;set;}
}

View:

@Html.LabelFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@* My Resource Uploader *@
@Html.EditorFor(model => model.UploadedResourceID, "ResourceUploader")

ResourceUploader EditorTemplate:

@model Guid?
@Html.LabelFor(model => model)
@Html.ValidationMessageFor(model => model)
@Html.HiddenFor(model => model)
<input 
       id="My_Custom_Ajax_Uploader_That_Populates_The_Hidden_Field"
       accept="@Html.ViewContext.ViewData.ModelMetadata.???????"
/>
... some ajax logic to upload the resource ...

I looked through ModelMetadata's fields in my template, but couldn't find a way to get FileExtensions attribute.

Was it helpful?

Solution

Found a somehow ugly way to achieve this:

var metaData = Html.ViewContext.ViewData.ModelMetadata;
var prop = metaData.ContainerType.GetProperty(metaData.PropertyName);
var fileExtAttrs = prop.GetCustomAttributes(typeof (FileExtensionsAttribute), false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top