繁体   English   中英

为什么HTML Helper EditorFor类型的文件会在C#和ASP.NET MVC中生成多个文件字段?

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

视图将生成3个文件输入字段。 这是屏幕截图:

屏幕抓图

但是,当我为HttpPostedFileBase添加EditorFor模板时,则可以完美运行。 我想知道为什么会这样。

这是我的模型:

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

控制器:

public class HomeController : Controller
{
   public ActionResult UploadFileData()
   {
       return 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>
}

在复杂对象上使用EditorFor()为该对象的每个属性生成默认模板(包括标签,表单控件和验证消息占位符)。 HttpPostedFileBase包含ContentTypeContentLengthFileName属性,因此生成了3个输入。 因为已包含type="file"additionalViewData ,所产生的输入是type="file"

您可以简单地使用

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

或者您可以为HttpPostedFileBase创建一个自定义EditorTemplate ,以便EditorFor()使用该模板,而不是默认模板。 但是该模板将需要包含@Html.TextBoxFor(m => m, new { type = "file" })所以除了包含LabelFor()ValidationMessageFor()并包含<div>元素,以便视图中所需的全部是@Html.EditorFor(m => m.ExcelFile)以生成所有html。 这样可以简化主视图,但是缺点是您不能例如在一个视图中使用col-md-10在另一个视图中使用col-md-8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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