I am storing images in Database as Binary Images successfully. I want to display these images in Edit form to modify and save changes. System.OutOfMemoryException' was thrown in Edit.cshtml form while displaying Binary Images from Database.
Can someone please correct my code.
Model class:
public class Accommodation
{
[Key]
public string A_Unique_Id { get; set; }
public byte[] Picture1 { get; set; }
public byte[] Picture2 { get; set; }
public byte[] Picture3 { get; set; }
}
// GET: /Accommodation/Edit/5
public ActionResult Edit(string id)
{
Accommodation accommodation = db.Accommodation.Find(id);
ViewBag.SelectedAustraliaStateId = new SelectList(db.AustraliaStates, "AustraliaStateId", "AustraliaStateName", accommodation.SelectedAustraliaStateId);
return View(accommodation);
}
// POST: /Accommodation/Edit/5
[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{
if (ModelState.IsValid)
{
db.Entry(accommodation).State = EntityState.Modified;
//the following line is for re-assigning back the DDL modified value.
accommodation.State = accommodation.SelectedAustraliaStateId;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(accommodation);
}
Edit.cshtml
<div class="editor-label">
@Html.LabelFor(model => model.Picture1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Picture1)
@Html.ValidationMessageFor(model => model.Picture1)
</div>
ERROR MESSAGE: Exception of type 'System.OutOfMemoryException' was thrown at line @Html.EditorFor(model => model.Picture1)
To display image in your view
View
<form method="post" enctype="multipart/form-data">
@{
if (Model.Picture1 != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture1);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="@imageSrc" width="100" height="100" />
}
}
<input type="file" name="photo" id="files" accept="image/*;capture=camera">
<button type="button">Submit</button>
</form>
Controller
[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{
if (Request.Files["files"] != null)
{
byte[] Image;
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
}
}
accommodation.Picture1=Image;
//your code to save data
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With