将HttpPostedFileBase传递给控制器​​方法

问题描述:

我只是试图创建一个表单,我可以输入名称并上传文件。这里的视图模型:将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。

我在这里做错了什么?

添加enctype到您的窗体:

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

请在表格一样添加编码类型

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

添加的编码类型的视图形式由下面的代码:

@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