I had this error when use upload file with razor page :
使用razor页面上传文件时出现此错误:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
指数超出范围。必须是非负数且小于集合的大小。参数名称:index
the error occurred here
这里发生了错误
var uploadedFile = Request.Files[0];
Controller:
控制器:
[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);
}
View:
视图:
@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>
}
1 个解决方案
#1
2
The error means, that the Request.Files
collection does not contain any item.
该错误意味着Request.Files集合不包含任何项目。
You can check with the Count
property for the number of files uploaded:
您可以使用Count属性检查上传的文件数:
if (Request.Files.Count > 0) {
var uploadedFile = Request.Files[0];
}
Check with fiddler what the browser is sending - maybe its an issue with the FileHelper
与fiddler一起检查浏览器发送的内容 - 也许是FileHelper的一个问题
#1
2
The error means, that the Request.Files
collection does not contain any item.
该错误意味着Request.Files集合不包含任何项目。
You can check with the Count
property for the number of files uploaded:
您可以使用Count属性检查上传的文件数:
if (Request.Files.Count > 0) {
var uploadedFile = Request.Files[0];
}
Check with fiddler what the browser is sending - maybe its an issue with the FileHelper
与fiddler一起检查浏览器发送的内容 - 也许是FileHelper的一个问题