将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" })
@Html.ValidationSummary() }
而我的控制器方法:
[HttpPost] public ActionResult Create(EmployeeViewModel viewModel) { // code here... }
问题是,当我发布到控制器方法时,Resume属性为null。 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" }))
通过以下代码以视图forms添加编码类型:
@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" })
@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路径将在基于目录的目录….你可以给你自己的路径,你希望保存文件