Reputation: 334
I'm trying to display images stored in sql database in binary format. I'm using razor syntax to retrieve images by changing its format to base64. The byte data is successfully retrieved, but never displayed as a picture format. Below is the code that I've tried so far. Thanks!
HotelInfo
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Travel.Context;
namespace Travel.Models.Hotel
{
public class HotelInfo
{
private int _hotelid;
private string _hotelname;
private string _hoteldesc;
private string _hotelprice;
private byte[] _hotelpicture;
//private HttpPostedFileBase _UploadedFile;
public HotelInfo()
{
this._hotelid = 0;
this._hotelname = string.Empty;
this._hoteldesc = string.Empty;
this._hotelprice = string.Empty;
}
[Key]
public int Hotelid
{
get
{
return _hotelid;
}
set
{
_hotelid = value;
}
}
public string Hotelname
{
get
{
return _hotelname;
}
set
{
_hotelname = value;
}
}
public string Hoteldesc
{
get
{
return _hoteldesc;
}
set
{
_hoteldesc = value;
}
}
public string Hotelprice
{
get
{
return _hotelprice;
}
set
{
_hotelprice = value;
}
}
public byte[] Hotelpicture
{
get
{
return _hotelpicture;
}
set
{
_hotelpicture = value;
}
}
}
}
HotelController.cs
public ActionResult HotelDescription()
{
return View(db.Hotels.ToList());
}
HotelDescription.cshtml
@model IEnumerable<Travel.Models.Hotel.HotelInfo>
@{
ViewBag.Title = "HotelDescription";
Layout = "~/Views/Shared/_Header.cshtml";
}
<h2>HotelDescription</h2>
<p>
@Html.ActionLink("Create New", "CreateHotel")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Hotelname)
</th>
<th>
@Html.DisplayNameFor(model => model.Hoteldesc)
</th>
<th>
@Html.DisplayNameFor(model => model.Hotelprice)
</th>
<th>
@Html.DisplayNameFor(model => model.Hotelpicture)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Hotelname)
</td>
<td>
@Html.DisplayFor(modelItem => item.Hoteldesc)
</td>
<td>
@Html.DisplayFor(modelItem => item.Hotelprice)
</td>
<td>
@{
var base64 = Convert.ToBase64String(item.Hotelpicture);
var imagesrc = string.Format("data:image/jpeg;base64,{0}", base64);
}
<img src = "imagesrc" style = 'max-height:100px;max-width:100px' />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Hotelid }) |
@Html.ActionLink("Details", "Details", new { id=item.Hotelid }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Hotelid })
</td>
</tr>
}
@section Scripts {
}
</table>
Upvotes: 0
Views: 599
Reputation: 880
Using Razor C# Syntax - Inline expressions (variables and functions) start with @.
Therefore if you edit
<img src = "imagesrc" style = 'max-height:100px;max-width:100px' />
To
<img src = "@imagesrc" style = 'max-height:100px;max-width:100px' />
Your code should work successfully.
Upvotes: 1