2017-08-29 38 views
-1

查看生成3個文件輸入字段。下面是截圖:爲什麼在C#和ASP.NET MVC中生成多個文件字段的類型文件的HTML幫助器EditorFor?

Screen grab of view

然而,當我添加EditorFor模板HttpPostedFileBase,那麼它完美的作品。我想知道爲什麼會發生這種情況。

這是我的模型:

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> 
} 
+0

使用'@ Html.TextBoxFor(m => m.ExcelFile,new {type =「file」})' –

+0

@Stephen Muecke我們不能使用Editor的方式來使用mvc5嗎?我認爲它應該工作,因爲我通過additionalviewdata(type = file)。這是一個錯誤還是什麼?這就是我發佈這個 –

+0

的原因(除非你爲'HttpPostedFileBase'類型創建'EditorTemplate')。我會盡快發表一個解釋行爲的答案。 –

回答

5

一個複雜的對象上的使用EditorFor()生成的默認模板(其包括標籤,表單控件和驗證消息佔位符)爲對象的每個屬性。 HttpPostedFileBase包含ContentType,ContentLengthFileName的屬性,因此生成3個輸入。由於您在additionalViewData中包含type="file",因此生成的輸入爲type="file"

您可以簡單地使用

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

,或者你可以創建一個自定義EditorTemplate爲typeof運算HttpPostedFileBase使EditorFor()使用該模板,而不是默認的模板。但該模板需要包含@Html.TextBoxFor(m => m, new { type = "file" }),因此除了包含LabelFor()ValidationMessageFor()幷包含<div>元素外,可能沒有太多意義,因此視圖中所需的全部內容都是生成所有html的@Html.EditorFor(m => m.ExcelFile)。這可以簡化主視圖,但缺點是,例如,您不能在一個視圖中使用col-md-10,在另一個視圖中使用col-md-8

相關問題