MVC在自定义编辑器模板中使用FileExtensionsAttribute

时间:2013-12-23 21:47:50

标签: asp.net asp.net-mvc asp.net-mvc-5 mvc-editor-templates

我正在尝试使用自定义资源上传器模板为我的模型上传资源,但我找不到获取FileExtensions数据注释属性元数据的方法:

视图模型

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

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

查看

@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 ...

我在模板中查看了ModelMetadata个字段,但找不到获取FileExtensions属性的方法。

1 个答案:

答案 0 :(得分:0)

找到了一种难以实现的方式:

var metaData = Html.ViewContext.ViewData.ModelMetadata;
var prop = metaData.ContainerType.GetProperty(metaData.PropertyName);
var fileExtAttrs = prop.GetCustomAttributes(typeof (FileExtensionsAttribute), false);