[英]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
包含ContentType
, ContentLength
和FileName
屬性,因此生成了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.