本文介绍了如何从数据库显示二进制图像以使用MVC 4编辑表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已成功将图像作为二进制图像存储在数据库中.我想在编辑"表单中显示这些图像,以修改和保存更改.显示数据库中的二进制图像时,以Edit.cshtml格式引发了System.OutOfMemoryException".
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.
模型类:
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
// 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
// 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
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>
错误消息:在行@Html.EditorFor(model => model.Picture1)
推荐答案
在视图中显示图像
查看
<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>
控制器
[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
}
这篇关于如何从数据库显示二进制图像以使用MVC 4编辑表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!