如何在MVC列表中显示图像?
问题描述:
我是最后一年的学生,从事五年规划,我有一个关于在二进制数据中存储图像的问题。我尝试了很多解决方案,我在Google上搜索过,但没有解决任何问题。如何在MVC列表中显示图像?
查看
@model IEnumerable<PictureServices.Picture>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
<tr>
@foreach (var item in Model)
{
<td>
@{
var base64 = Convert.ToBase64String(item.image);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
}
<img src='@imgsrc' style="max-width:100px; max-height:100px;">
</td>
模型
public class Picture
{
public int id { get; set; }
public byte[] image { get; set; }
public string name { get; set; }
}
控制器
public class CarServicesController : Controller
{
TestingEntities db = new TestingEntities();
public ActionResult Index()
{
Picture ds = new Picture();
var item = (from d in db.Pictures
select d).ToList();
return View(item);
}
答
可以转换字节数组到基座64串并使用它作为图像源。您可以使用Convert.ToBase64String
来执行此操作。你必须做的一件事是在尝试转换字节数组之前检查null
,因为它可能为空。
@model IEnumerable<PictureServices.Picture>
<table class="table table-striped">
@foreach (var r in Model)
{
<tr>
<td>@r.Id</td>
<td>@r.Name</td>
<td>
@if (r.Image != null)
{
var imgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(r.Image)}";
<img src="@imgSrc" alt="@r.Name" />
}
</td>
</tr>
}
</table>
我也建议使用PascalCasing为C#类特性(Name
代替name
)。
我按照您的指示尝试了这一个,但它没有起作用,调试在断点处停止。 –
你有没有例外? – Shyju
显示没有任何错误,浏览器稍后搜索后重定向回Controller文件。 VS中没有显示任何错误。 –