Generate file upload input for property with "DataType.Upload" attribute?

asp.net, asp.net-mvc

Solution

Change your image control to this,

  @Html.TextBoxFor(m => m.ImageUpload, new { type = "file", name = "Files" })

Problem

I have the following view model. ``` public class MyViewModel { [DataType(DataType.Upload)] public HttpPostedFileBase ImageUpload { get; set; } public int VenueId { get; set; } public virtual Venue Venue { get; set; } .... // other properties } ``` I'm following this page http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/ to create image upload control. Here is the view code. ``` @using (Html.BeginForm("Create", "Event", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.VenueId, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.VenueId) @Html.ValidationMessageFor(model => model.VenueId) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ImageUpload, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ImageUpload) @Html.ValidationMessageFor(model => model.ImageUpload) </div> </div> } ``` However, it generates three text boxes instead of file upload input control? The following Html code. ``` <div class="col-md-10"> <div class="editor-label"><label for="ImageUpload_ContentLength">ContentLength</label></div> <div class="editor-field"><input name="ImageUpload.ContentLength" class="text-box single-line" id="ImageUpload_ContentLength" type="number" value="" data-val-required="The ContentLength field is required." data-val-number="The field ContentLength must be a number." data-val="true"> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="ImageUpload.ContentLength"></span></div> <div class="editor-label"><label for="ImageUpload_ContentType">ContentType</label></div> <div class="editor-field"><input name="ImageUpload.ContentType" class="text-box single-line" id="ImageUpload_ContentType" type="text" value=""> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="ImageUpload.ContentType"></span></div> <div class="editor-label"><label for="ImageUpload_FileName">FileName</label></div> <div class="editor-field"><input name="ImageUpload.FileName" class="text-box single-line" id="ImageUpload_FileName" type="text" value=""> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="ImageUpload.FileName"></span></div> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="ImageUpload"></span> </div> ```

Original source