我在将上传文件与剃刀页面一起使用时遇到此错误:
指数超出范围。必须是非负数且小于集合的大小。 参数名称:索引
此处发生错误
var uploadedFile = Request.Files[0];
控制器:
[HttpPost]
public ActionResult Create(Category category)
{
if (ModelState.IsValid)
{
var fileSavePath = "";
var fileName = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("../../Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
视图:
@using (Html.BeginForm("Create", "Category", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.Path)
</div>
<div class="editor-field create-Bt3">
@FileUpload.GetHtml(
initialNumberOfFiles: 1,
allowMoreFilesToBeAdded: false,
includeFormTag: false,
uploadText: "Upload")
</div>
}
该错误意味着Request.Files
集合不包含任何项。
您可以使用 Count
属性检查上传的文件数:
if (Request.Files.Count > 0) {
var uploadedFile = Request.Files[0];
}
与小提琴手一起检查浏览器正在发送的内容 - 也许是FileHelper
的问题