0

hi im new to C# and i am struggling whith this proplem.

i am trying to upload an image and save it to a local folder, but i am geting a NullReferenceException when i try it..

my controller

[HttpPost]
    public ActionResult Index(Picture pic)
    {
        Picture newPix = pic;
        if (newPix.File.ContentLength > 0)
        {
            var fileName = Path.GetFileName(pic.File.FileName);
            //var fileName = pic.File.FileName;
            var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
            pic.File.SaveAs(path);
        }
        return RedirectToAction("Index");
    }

my view

<div class="row">
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr>
            <td>File:</td>
            <td><input type="file" id="File" /></td>
            <td><input type="submit" name="submit" value="Upload" /></td>
        </tr>

    </table>
}

my model

{
        public HttpPostedFileBase File { get; set; }
    }

when i debug, I can see that pic in the controller is NULL,, am i sending the file wrong to the controler from the form?

tereško
  • 58,060
  • 25
  • 98
  • 150
user3396248
  • 61
  • 1
  • 1
  • 5

2 Answers2

2

Your input file id is "File" and the action result is expecting "pic"

Update your HTML to

<td><input type="file" id="file" name="file" /></td>

Update your your Action Method to

 public ActionResult Index(HttpPostedFileBase file)
    {
        Picture newPix = file;
        if (newPix.File.ContentLength > 0)
        {
            var fileName = Path.GetFileName(pic.File.FileName);
            //var fileName = pic.File.FileName;
            var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
            pic.File.SaveAs(path);
        }
        return RedirectToAction("Index");
    }
Moe
  • 1,599
  • 11
  • 16
1

You are getting the null reference exception when you tried to read newPix.File property. newPix is null and you are trying to read some property of null.

It is null because Model binding failed! Model binding happens when your view model property names and your form element names are same. Your form element is missing the name attribute. Add it and it should work.

<input type="file" name="File" id="File" />

Next time when you get an error, put a visual studio break point in your code and inspect the variable values and you will get an idea why it failed.

Shyju
  • 214,206
  • 104
  • 411
  • 497