2014-10-08 42 views
0

我创建的文件(文件和FileFor)的HTML帮助如下时:HttpPostedFileBase总是空使用自定义的HTML帮助

public static IHtmlString File(this HtmlHelper html, String text, String name, IDictionary<String, Object> attributes) 
{ 
    // Code snip 
    TagBuilder input = new TagBuilder("input"); 
    input.MergeAttribute("type", "file"); 
    input.MergeAttribute("name", name, true); 
    input.GenerateId(name); 

    return // ... 
} 

public static IHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, String text) 
    where TModel : class 
{ 
    return FileFor(html, expression, text, null); 
} 

一切正常,除非我有以下型号:

public class AdvertViewNewModel : ViewModel 
{ 
    public AdvertModel Advert { get; set; } 

    public class AdvertModel 
    { 
     public HttpPostedFileBase Image { get; set; } 
     public String Name { get; set; } 
    } 
} 

的问题是,在这种情况下,ASP.NET呈现输入为:

<input type="file" name="Advert.Image" id="Advert_Image"> 

而我的HTML帮助呈现为:

<input type="file" name="Image" id="Image"> 

如果我没有孩子班,这将是好的。

我该如何解决这个问题?

UPDATE

我FileFor代码:

public static IHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, String text, IDictionary<String, Object> attributes) where TModel : class { 

    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 

    String field = ExpressionHelper.GetExpressionText(expression); 

    String name = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(field); 

    return File(html, text, metadata.DisplayName ?? metadata.PropertyName ?? field, attributes == null ? new RouteValueDictionary() : attributes); 

} 
+1

请发布'FileFor'如何从'expression'中读取名称 – beautifulcoder 2014-10-08 19:35:43

+0

是的,我刚刚更新以包含该代码。基本上我使用:String name = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(field); – 2014-10-08 20:02:52

回答

0

变化

metadata.DisplayName ?? metadata.PropertyName ?? field 

metadata.PropertyName 

我认为这是捡DisplayName而不是PropertyName。