[RESOLVED]HttpPostedFileBase always null when using a custom Html Helper

Hello,

I created an HTML helper for file (File and FileFor) as follows:

    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);
    } 

Everything works fine unless I have the following model:

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

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

The problem is that in this case ASP.NET renders the input as:

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

And my Html Helper renders it as:

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

Which would be ok if I would not have a child class.

My FileFor code:

    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);

    }

How can I solve this?

Thank You,

Miguel

Do you have 

enctype="multipart/form-data"

?

Leave a Reply