I want to insert the image into an Image folder and add the image path into database using entity framework.My Model is,
public class Orphan
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public bool Disable { get; set; }
public DateTime JoinedDate { get; set; }
public DateTime? LeaveDate { get; set; }
public Carer Carer { get; set; }
public string CarerName { get; set; }
public string ImagePath { get; set; }
}
THis is the view model,
public partial class OrphanViewModel
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
[Required]
public bool Disable { get; set; }
[Required]
public string CarerName { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
}
This is the view of imagepath.
<div class="form-group">
@Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" required />
</div>
</div>
And here is the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OrphanViewModel ovm)
{
string fileName = Path.GetFileNameWithoutExtension(ovm.ImageFile.FileName);
string extension = Path.GetExtension(ovm.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
ovm.ImagePath = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
ovm.ImageFile.SaveAs(fileName);
if (ModelState.IsValid)
{
db.Orphans.Add(new Orphan()
{
FirstName = ovm.FirstName,
LastName = ovm.LastName,
Age = ovm.Age,
Gender = ovm.Gender,
Disable = ovm.Disable,
JoinedDate = DateTime.Now,
CarerName = ovm.CarerName,
ImagePath = ovm.ImagePath
});
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ovm);
}
So the problem i am facing is here it says in ovm.ImageFile {"Object reference not set to an instance of an object."}.HELP
string fileName = Path.GetFileNameWithoutExtension(ovm.ImageFile.FileName);