I'm trying to save files into my Db with this code:
[HttpPost, ActionName("CandidateCreate")]
[ValidateAntiForgeryToken]
public IActionResult CandidateCreatePost([Bind("Name,Number,Profile,CV,CVID")]Candidate candidate, IFormFile Corriculum)
{
try
{
if (ModelState.IsValid)
{
//if (Corriculum != null)
//{
// if (Corriculum.Length > 0)
// {
using (var applicationContext = new ApplicationContext())
{
byte[] p1 = null;
using (var fs1 = Corriculum.OpenReadStream())
using (var ms1 = new MemoryStream())
{
fs1.CopyTo(ms1);
p1 = ms1.ToArray();
}
candidate.CV = p1;
// }
//}
}
//candidate.CV = p1;
candidateRepository.Add(candidate);
candidateRepository.SaveChanges();
return RedirectToAction("Candidate");
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View();
}
I have changed my code to this, but Curriculum is always null? why is that?? I'm getting this error "NullReferenceException: Object reference not set to an instance of an object."
答案 0 :(得分:0)
一段时间后,我努力使它以这种方式工作:
[HttpPost, ActionName("CandidateCreate")]
[ValidateAntiForgeryToken]
public IActionResult CandidateCreatePost([Bind("Name,Number,Profile,CV,CVID")] Candidate candidate, IFormFile CV)
{
if (ModelState.IsValid)
{
if (CV != null)
{
if (CV.Length > 0)
{
byte[] p1 = null;
using (var fs1 = CV.OpenReadStream())
using (var ms1 = new MemoryStream())
{
fs1.CopyTo(ms1);
p1 = ms1.ToArray();
}
candidate.CVNAME = CV.FileName;
candidate.CV = p1;
}
}
using (var applicationContext = new ApplicationContext())
{
candidateRepository.Add(candidate);
candidateRepository.SaveChanges();
return RedirectToAction("Candidate");
}
}
return View();
}