我犯了个错误
处理请求时发生了未处理的异常。NullReferenceException:对象引用没有设置为对象的实例。
为什么是空的?请帮忙解决!!
编辑:错误行是
themobilesuits.PicFile = Path.GetFileName(thePic.FileName);[Authorize]
[HttpPost]
public IActionResult Add(TheMobileSuit themobilesuits, IFormFile thePic)
{
DbSet<TheMobileSuit> dbs = _dbContext.TheMobileSuit;
themobilesuits.PicFile = Path.GetFileName(thePic.FileName);
dbs.Add(themobilesuits);
if (_dbContext.SaveChanges() == 1)
{
string fname = "Images/" + themobilesuits.PicFile;
if (UploadFile(thePic, fname))
{
TempData["Msg"] = "New Order Added!";
}
else
{
return BadRequest();
}
}
else
TempData["Msg"] = "Error.";
return RedirectToAction("Index");
}
private bool UploadFile(IFormFile ufile, string fname)
{
if (ufile.Length > 0)
{
string fullpath = Path.Combine(_env.WebRootPath, fname);
using (var fileStream =
new FileStream(fullpath, FileMode.Create))
{
ufile.CopyToAsync(fileStream);
}
return true;
}
return false;
}
View:
<div class="form-group">
<label class="control-label col-sm-2">Photo:</label>
<div class="col-sm-4">
<input type="file" name="thePic"
class="form-control" />
</div>
</div>发布于 2019-11-29 06:46:46
我认为您还没有在标记中使用: enctype = "multipart/form-data“。例:
<form method=post action="..."enctype = "multipart/form-data">发布于 2020-09-18 16:39:19
我也犯了同样的错误,我已经修好了。
(1)在你看来-
<input type="file" name="**thePic**" class="form-control" />(2)在你的总监及行动中-
public IActionResult Add(TheMobileSuit themobilesuits, IFormFile **thePic**){
(3)在ViewModel中,您的财产名也是thePic。
**这三个参数的名称必须相同.**(您的名字是"thePic")
我花了4个小时才发现这个问题。希望它对你有帮助。谢谢。
https://stackoverflow.com/questions/59098086
复制相似问题