我只是想创建一个表单,我可以在其中输入名称并上传文件。这是视图模型:
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...
}
问题是当我发布到控制器方法时,Resume属性为null。 Name属性传递得很好,但不是HttpPostedFileBase。
我在这里做错了吗?
答案 0 :(得分:8)
将enctype添加到表单中:
@Html.BeginForm("Create", "Employees", FormMethod.Post,
new{ enctype="multipart/form-data"})
答案 1 :(得分:2)
请在表单中添加编码类型,
@using (Html.BeginForm("Create","Employees",FormMethod.Post, new { enctype = "multipart/form-data" }))
答案 2 :(得分: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);
}
}
}
}
}
}
我的路径将位于基于目录的目录....你可以给自己想要保存文件的路径