简体   繁体   中英

Why is the HTML helper EditorFor of type file generating multiple file fields in C# and ASP.NET MVC?

View generates 3 file input fields. Here is the screenshot:

屏幕抓图

However, when I add EditorFor template for HttpPostedFileBase , then it works perfectly. I want to know why is this happening.

This is my model:

public class UploadFileViewModel
{
        [Required]
        [Display(Name ="Select Excel File")]
        public HttpPostedFileBase ExcelFile { get; set; }
}

The controller:

public class HomeController : Controller
{
   public ActionResult UploadFileData()
   {
       return View();
   }
}

The view:

@model DemoProject.Models.UploadFileViewModel
@{
    ViewBag.Title = "Upload File Data";
}

<h2>Upload File Data</h2>
<p class="alert-success">@ViewBag.Success</p>
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken();
    @Html.ValidationSummary("", new { @class = "text-danger" });

    <div class="form-horizontal">
        <div class="form-group">            
            @Html.LabelFor(model=>model.ExcelFile, htmlAttributes: new {@class="control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model=>model.ExcelFile, new { htmlAttributes = new { type = "file" } })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Upload" class="btn btn-default" />
            </div>
        </div>

    </div>
}

Using EditorFor() on a complex object generates the default template (which includes a label, form control and validation message placeholder) for each property of the object. HttpPostedFileBase contains properties for ContentType , ContentLength and FileName so 3 inputs are generated. Because you have included type="file" in the additionalViewData , the inputs generated are type="file" .

You can simply use

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

or you could create a custom EditorTemplate for typeof HttpPostedFileBase so that EditorFor() uses that template, rather than the default template. But that template would need to include @Html.TextBoxFor(m => m, new { type = "file" }) so there is probably not much point, other than to include the LabelFor() and ValidationMessageFor() and enclosing <div> elements so that all that's needed in the view is @Html.EditorFor(m => m.ExcelFile) to generate all the html. This can simplify the main view, but the disadvantage is that you cannot for example, have col-md-10 in one view and col-md-8 in another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM