Or you could do it properly:
In your HtmlHelper Extension class:
public static MvcHtmlString FileFor(this HtmlHelper helper, Expression> expression)
{
return helper.FileFor(expression, null);
}
public static MvcHtmlString FileFor(this HtmlHelper helper, Expression> expression, object htmlAttributes)
{
var builder = new TagBuilder("input");
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
builder.GenerateId(id);
builder.MergeAttribute("name", id);
builder.MergeAttribute("type", "file");
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
This line:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.
Create the correct property in the model:
public HttpPostedFileBase NewFile { get; set; }
Then you need to make sure your form will send files:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
Then here's your helper:
@Html.FileFor(x => x.NewFile)