我遇到错误
处理请求时发生未处理的异常。 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>
答案 0 :(得分:0)
我认为您尚未使用: 标签中的enctype =“ multipart / form-data”。 例如:
<form method=post action="..."enctype = "multipart/form-data">
答案 1 :(得分:0)
我有相同的错误,并且已经解决。
(1)在您的视图中-
<input type="file" name="**thePic**" class="form-control" />
(2)在您的控制器和操作中-
public IActionResult Add(TheMobileSuit themobilesuits, IFormFile **thePic**)
{
(3)在ViewModel中,您的属性名称也是 thePic 。
**这三个参数的名称必须相同。 (您的名字是“ thePic”)
我已经花了4个小时来发现此问题。 希望对您有帮助。谢谢。