Below the controller, I get the uploadImage parameter and I do Update DB, but the parameter is always null.

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Model,Color,YearOfIssue,Plate,Image")] Cars cars, HttpPostedFileBase uploadImage) { if (uploadImage != null) { byte[] imageData = null; using (var binaryReader = new BinaryReader(uploadImage.InputStream)) imageData = binaryReader.ReadBytes(uploadImage.ContentLength); cars.Image = imageData; } if (ModelState.IsValid) { db.Entry(cars).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(cars); } 

Slice from the Edit view

  <div class="form-group"> @Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <input type="file" name="uploadImage" class="form-control" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Применить" class="btn btn-primary" /> </div> </div> 
  • What could be the problem? In the debugger, when I select a file on the site, it skips the entire if condition code (uploadImage! = Null) and updates only other data. - Kryshtop

3 answers 3

Try to put an additional condition

 if (uploadImage != null && uploadImage.ContentLength > 0) { } 
  • if a field is used to send a file (input type = "file"), the enctype attribute should be defined as multipart / form-data. - Kryshtop

In order for the files to be sent from the browser form, you need to add the enctype attribute to the form tag with the value multipart / form-data:

 <form method="post" enctype="multipart/form-data"> <input type="file" name="uploadImage" /> </form> 

More details about the attribute: http://htmlbook.ru/html/form/enctype

multipart / form-data Data is not encoded. This value is used when sending files.

    must have:

     @using (Html.BeginForm("Edit", "Cars", FormMethod.Post, new { enctype = "multipart/form-data" })) 

    PROFIT !!!

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky
    • If a field is used to send a file (input type = "file"), the enctype attribute should be defined as multipart / form-data. - Kryshtop