2012-03-01 213 views
8

我只是試圖創建一個表單,我可以輸入名稱並上傳文件。這裏的視圖模型:將HttpPostedFileBase傳遞給控制器​​方法

public class EmployeeViewModel 
{ 
    [ScaffoldColumn(false)] 
    public int EmployeeId { get; set; } 

    public string Name { get; set; } 

    public HttpPostedFileBase Resume { get; set; } 
} 

我的觀點:

@using (Html.BeginForm("Create", "Employees", FormMethod.Post)) 
{ 
    @Html.TextBoxFor(model => model.Name) 

    @Html.TextBoxFor(model => model.Resume, new { type = "file" }) 

    <p> 
     <input type="submit" value="Save" /> 
    </p> 

    @Html.ValidationSummary() 
} 

而且我控制器的方法:

[HttpPost] 
public ActionResult Create(EmployeeViewModel viewModel) 
{ 
    // code here... 
} 

的問題是,當我張貼到控制器的方法,簡歷屬性空值。 Name屬性被傳遞得很好,但不是HttpPostedFileBase。

我在這裏做錯了什麼?

回答

8

添加enctype到您的窗體:

@Html.BeginForm("Create", "Employees", FormMethod.Post, 
       new{ enctype="multipart/form-data"}) 
2

請在表格一樣添加編碼類型

@using (Html.BeginForm("Create","Employees",FormMethod.Post, new { enctype = "multipart/form-data" })) 
2

添加的編碼類型的視圖形式由下面的代碼:

@using (Html.BeginForm("Create", "Employees", FormMethod.Post,new{ enctype="multipart/form-data"})) 
{ 
    @Html.TextBoxFor(model => model.Name) 

    @Html.TextBoxFor(model => model.Resume, new { type = "file" }) 

    <p> 
    <input type="submit" value="Save" /> 
    </p> 
@Html.ValidationSummary() 
} 

在您的控制器中添加以下代碼,

[HttpPost] 
public ActionResult Create(EmployeeViewModel viewModel) 
{ 
     if (Request.Files.Count > 0) 
     { 
      foreach (string file in Request.Files) 
      { 
       string pathFile = string.Empty; 
       if (file != null) 
       { 
        string path = string.Empty; 
        string fileName = string.Empty; 
        string fullPath = string.Empty; 
        path = AppDomain.CurrentDomain.BaseDirectory + "directory where you want to upload file";//here give the directory where you want to save your file 
        if (!System.IO.Directory.Exists(path))//if path do not exit 
        { 
         System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "directory_name/");//if given directory dont exist, it creates with give directory name 
        } 
        fileName = Request.Files[file].FileName; 

        fullPath = Path.Combine(path, fileName); 
        if (!System.IO.File.Exists(fullPath)) 
        { 

         if (fileName != null && fileName.Trim().Length > 0) 
         { 
          Request.Files[file].SaveAs(fullPath); 
         } 
        } 
       } 
      } 
     } 
} 

我asssumed路徑將是basedirectory的目錄中....,你希望保存文件

+0

+1約Html.editor的是什麼,而不是Html.TextBoxFor你可以給自己的路 – Nikos 2012-12-21 21:56:05