I have a form to store some records in events table in database along with the path of an uploaded file.
But when i click the Save button, it generates the following error:
Object reference not set to an instance of an object.
This is my model:
public class events1
{
public int Id { get; set; }
public string title { get; set; }
public string report { get; set; }
public string image1 { get; set; }
public string image2 { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
}
This is my controller
public ActionResult Index()
{
var evt = _context.evt1;
if (evt==null)
{
return Content("No events registered in database");
}
return View(evt);
}
public ActionResult Add_New()
{
return View();
}
[HttpPost]
public ActionResult Save(events1 e)
{
string filename = Path.GetFileNameWithoutExtension(e.ImageFile.FileName);
string extension = Path.GetExtension(e.ImageFile.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.image1 = "~/Uploaded_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/Uploaded_Files/"), filename);
e.ImageFile.SaveAs(filename);
_context.evt1.Add(e);
_context.SaveChanges();
ModelState.Clear();
return RedirectToAction("Index","Events1");
}
And this is the view:
@model UploadFile_Button.Models.events1
@{
ViewBag.Title = "Add_New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Save", "Events1"))
{
<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(a => a.report)
@Html.TextBoxFor(a => a.report, new { @class = "form-control" })
</div>
<div class="form-group">
<input type="file" name="ImageFile"/>
</div>
<div class="form-group">
@Html.LabelFor(a => a.image2)
@Html.TextBoxFor(a => a.image2, new { @class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Save</button>
}
I have to mention when it generates the error, it also highlights this line of my code in RED color:
string filename = Path.GetFileNameWithoutExtension(e.ImageFile.FileName);