0

i am trying to upload file from my PC to local Database with ASP.NET and Getting Object reference not set to an instance of an object. my Controller

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Jobs jobs, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {      
                string path = Path.Combine(Server.MapPath("~/Upload"), upload.FileName);
                upload.SaveAs(path);
                jobs.JobsImg = upload.FileName;
                db.Jobs.Add(jobs);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(jobs);
        }

Views

@model FindJobs.Models.Jobs

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_MainLayout.cshtml";
}

<h2>Create</h2>
@using (Html.BeginForm("Create" , "Jobs" , FormMethod.Post , new {enctype = "multipart / form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="form-group">
            @Html.LabelFor(model => model.JobsImg, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="upload" />
                @Html.ValidationMessageFor(model => model.JobsImg, "", new { @class = "text-danger" })
            </div>
        </div>

the upload file its image. and how can I identify null value

best Regards

  • 1
    try to remove the space `{enctype = "multipart / form-data" }` to `{enctype = "multipart/form-data" }` – jishan siddique Nov 01 '21 at 05:34
  • Hi, start by adding a breakpoint on the controller action. This can be done by selecting the code line in visual studio and pressing F9, you can then step through the code using F10 until you find the line with the NULL object. Best way to find a NULL. – B.Spangenberg Nov 01 '21 at 06:44
  • Razor pages also allow you to debug them with the visual studio debug tools. – B.Spangenberg Nov 01 '21 at 06:45
  • 1
    From a quick look, my best guess is that your parameters on the post method could be null. 'public ActionResult Create(Jobs jobs, HttpPostedFileBase upload)' I don't see you passing any data to the method for those parmas on the razor page. @using (Html.BeginForm("Create" , "Jobs" , FormMethod.Post , new {enctype = "multipart / form-data" })) – B.Spangenberg Nov 01 '21 at 06:47
  • Please read through this answer below. https://stackoverflow.com/questions/20942926/pass-multiple-parameters-in-html-beginform-mvc4-controller-action – B.Spangenberg Nov 01 '21 at 06:49

0 Answers0